|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to calculate the length of the Longest Increasing Subsequence (LIS) |
| 4 | + // using a bottom-up dynamic programming approach. |
| 5 | + int solve(vector<int>& nums) { |
| 6 | + int n = nums.size(); // Get the size of the array. |
| 7 | + |
| 8 | + // Create a 2D DP table initialized with 0. |
| 9 | + // dp[currIndex][prevIndex+1] represents the length of LIS starting at `currIndex` |
| 10 | + // with the previous element being `nums[prevIndex]`. |
| 11 | + vector<vector<int>> dp(n + 1, vector<int>(n + 1, 0)); |
| 12 | + |
| 13 | + // Iterate over the array in reverse order for `currIndex`. |
| 14 | + for (int currIndex = n - 1; currIndex >= 0; currIndex--) { |
| 15 | + // Iterate over the possible values of `prevIndex` in reverse order. |
| 16 | + for (int prevIndex = currIndex - 1; prevIndex >= -1; prevIndex--) { |
| 17 | + |
| 18 | + // Option 1: Include the current element in the LIS. |
| 19 | + int include = 0; |
| 20 | + if (prevIndex == -1 || nums[currIndex] > nums[prevIndex]) { |
| 21 | + // If there is no previous element or the current element is greater, |
| 22 | + // include the current element in the LIS. |
| 23 | + include = 1 + dp[currIndex + 1][currIndex + 1]; |
| 24 | + } |
| 25 | + |
| 26 | + // Option 2: Exclude the current element and proceed. |
| 27 | + int exclude = dp[currIndex + 1][prevIndex + 1]; |
| 28 | + |
| 29 | + // Take the maximum of including or excluding the current element. |
| 30 | + dp[currIndex][prevIndex + 1] = max(include, exclude); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + // Return the result for the entire array (starting at index 0 with no previous element). |
| 35 | + return dp[0][0]; |
| 36 | + } |
| 37 | + |
| 38 | + // Main function to calculate the length of the Longest Increasing Subsequence (LIS). |
| 39 | + int lengthOfLIS(vector<int>& nums) { |
| 40 | + int n = nums.size(); // Get the size of the array. |
| 41 | + return solve(nums); // Call the helper function to solve the problem. |
| 42 | + } |
| 43 | +}; |
0 commit comments