|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to calculate the length of the Longest Increasing Subsequence (LIS) |
| 4 | + // using a space-optimized dynamic programming approach. |
| 5 | + int solve(vector<int>& nums) { |
| 6 | + int n = nums.size(); // Get the size of the array. |
| 7 | + |
| 8 | + // Create two 1D DP arrays, `curr` and `next`, initialized with 0. |
| 9 | + // `curr` represents the current state, and `next` represents the state of the next row in the 2D DP table. |
| 10 | + vector<int> curr(n + 1, 0); |
| 11 | + vector<int> next(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 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 + next[currIndex + 1]; |
| 24 | + } |
| 25 | + |
| 26 | + // Option 2: Exclude the current element and proceed. |
| 27 | + int exclude = next[prevIndex + 1]; |
| 28 | + |
| 29 | + // Store the maximum of including or excluding the current element in `curr`. |
| 30 | + curr[prevIndex + 1] = max(include, exclude); |
| 31 | + } |
| 32 | + |
| 33 | + // Update `next` to the current state for the next iteration. |
| 34 | + next = curr; |
| 35 | + } |
| 36 | + |
| 37 | + // The result for the entire array (starting at index 0 with no previous element) is stored in `curr[0]`. |
| 38 | + return curr[0]; |
| 39 | + } |
| 40 | + |
| 41 | + // Main function to calculate the length of the Longest Increasing Subsequence (LIS). |
| 42 | + int lengthOfLIS(vector<int>& nums) { |
| 43 | + int n = nums.size(); // Get the size of the array. |
| 44 | + return solve(nums); // Call the helper function to solve the problem. |
| 45 | + } |
| 46 | +}; |
0 commit comments