File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed
24 - Dynamic Programming Problems/19 - Longest Increasing Subsequence Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ // Helper function to calculate the length of the Longest Increasing Subsequence (LIS)
4+ // using a simple dynamic programming approach.
5+ int solve (vector<int >& nums) {
6+ int n = nums.size (); // Get the size of the array.
7+
8+ // Create a 1D DP array where dp[i] represents the length of the LIS ending at index `i`.
9+ vector<int > dp (n, 1 );
10+
11+ // Iterate through the array to build the DP table.
12+ for (int currIndex = 1 ; currIndex < n; currIndex++) {
13+ // For each `currIndex`, check all previous indices (`prevIndex`) to find
14+ // the longest increasing subsequence that can be extended by `nums[currIndex]`.
15+ for (int prevIndex = 0 ; prevIndex < currIndex; prevIndex++) {
16+ // If the current element is greater than the previous element,
17+ // update dp[currIndex] to include the LIS ending at `prevIndex`.
18+ if (nums[currIndex] > nums[prevIndex]) {
19+ dp[currIndex] = max (dp[currIndex], dp[prevIndex] + 1 );
20+ }
21+ }
22+ }
23+
24+ // The length of the LIS is the maximum value in the DP array.
25+ // Use `max_element` to find the maximum value in the DP array.
26+ return *max_element (dp.begin (), dp.end ());
27+ }
28+
29+ // Main function to calculate the length of the Longest Increasing Subsequence (LIS).
30+ int lengthOfLIS (vector<int >& nums) {
31+ int n = nums.size (); // Get the size of the array.
32+ return solve (nums); // Call the helper function to solve the problem.
33+ }
34+ };
You can’t perform that action at this time.
0 commit comments