|
| 1 | +class Solution { |
| 2 | +public: |
| 3 | + // Helper function to find the length of the Longest Increasing Subsequence (LIS) |
| 4 | + // using recursion. |
| 5 | + // Parameters: |
| 6 | + // - nums: The array of numbers. |
| 7 | + // - currIndex: The current index being considered. |
| 8 | + // - prevIndex: The index of the previous element included in the subsequence. |
| 9 | + int solve(vector<int>& nums, int currIndex, int prevIndex) { |
| 10 | + int n = nums.size(); // Get the size of the array. |
| 11 | + |
| 12 | + // Base case: If we reach the end of the array, return 0. |
| 13 | + if (currIndex == n) return 0; |
| 14 | + |
| 15 | + int include = 0; // Variable to store the result of including nums[currIndex]. |
| 16 | + |
| 17 | + // Check if the current element can be included in the subsequence. |
| 18 | + // It can be included if: |
| 19 | + // - There is no previous element included (prevIndex == -1), OR |
| 20 | + // - The current element is greater than the last included element. |
| 21 | + if (prevIndex == -1 || nums[currIndex] > nums[prevIndex]) { |
| 22 | + include = 1 + solve(nums, currIndex + 1, currIndex); // Include nums[currIndex]. |
| 23 | + } |
| 24 | + |
| 25 | + // Exclude the current element and move to the next. |
| 26 | + int exclude = solve(nums, currIndex + 1, prevIndex); |
| 27 | + |
| 28 | + // Return the maximum of including or excluding the current element. |
| 29 | + return max(include, exclude); |
| 30 | + } |
| 31 | + |
| 32 | + // Main function to calculate the length of the Longest Increasing Subsequence. |
| 33 | + int lengthOfLIS(vector<int>& nums) { |
| 34 | + return solve(nums, 0, -1); // Start with the first element and no previous element. |
| 35 | + } |
| 36 | +}; |
0 commit comments