Skip to content

Commit 296608b

Browse files
authored
Create 05 - Space Optimized - 2 | DP | Approach.cpp
1 parent 4f7d894 commit 296608b

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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+
};

0 commit comments

Comments
 (0)