From 19d04de2abcfc9a9cd1c82d132a561f5033cfa12 Mon Sep 17 00:00:00 2001 From: Mohd Rashid Ansari <92138079+rashid2002@users.noreply.github.com> Date: Fri, 8 Nov 2024 16:40:15 +0530 Subject: [PATCH] Create longest increasing subsequence --- DP/longest increasing subsequence | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 DP/longest increasing subsequence diff --git a/DP/longest increasing subsequence b/DP/longest increasing subsequence new file mode 100644 index 000000000..6020ed5de --- /dev/null +++ b/DP/longest increasing subsequence @@ -0,0 +1,29 @@ +#include +#include +#include + +int lengthOfLIS(const std::vector& nums) { + int n = nums.size(); + if (n == 0) return 0; + + // dp[i] stores the length of LIS ending at index i + std::vector dp(n, 1); + int maxLength = 1; + + for (int i = 1; i < n; i++) { + for (int j = 0; j < i; j++) { + if (nums[i] > nums[j]) { // Check if nums[i] can extend the sequence at nums[j] + dp[i] = std::max(dp[i], dp[j] + 1); + } + } + maxLength = std::max(maxLength, dp[i]); + } + + return maxLength; +} + +int main() { + std::vector nums = {10, 9, 2, 5, 3, 7, 101, 18}; + std::cout << "Length of Longest Increasing Subsequence: " << lengthOfLIS(nums) << std::endl; + return 0; +}