Skip to content

Commit a864d64

Browse files
authored
Create 06 - DP With Binary Search Approach.cpp
1 parent 296608b commit a864d64

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
class Solution {
2+
public:
3+
// Helper function to calculate the length of the Longest Increasing Subsequence (LIS)
4+
// using a more efficient approach with binary search.
5+
int solve(vector<int>& nums) {
6+
int n = nums.size(); // Get the size of the array.
7+
8+
// Create a vector `ans` to store the elements of the current LIS.
9+
// It will not necessarily be the actual LIS but will have the same length.
10+
vector<int> ans;
11+
12+
// Add the first element to the LIS tracker.
13+
ans.push_back(nums[0]);
14+
15+
// Iterate over the rest of the elements in the array.
16+
for (int i = 1; i < n; i++) {
17+
// If the current element is greater than the last element of `ans`,
18+
// it extends the LIS, so add it to the end of `ans`.
19+
if (nums[i] > ans.back()) {
20+
ans.push_back(nums[i]);
21+
}
22+
// Otherwise, replace the smallest element in `ans` that is greater than
23+
// or equal to the current element using `lower_bound`.
24+
else {
25+
int index = lower_bound(ans.begin(), ans.end(), nums[i]) - ans.begin();
26+
ans[index] = nums[i];
27+
}
28+
}
29+
30+
// The size of the `ans` vector represents the length of the LIS.
31+
return ans.size();
32+
}
33+
34+
// Main function to calculate the length of the Longest Increasing Subsequence (LIS).
35+
int lengthOfLIS(vector<int>& nums) {
36+
int n = nums.size(); // Get the size of the array.
37+
return solve(nums); // Call the helper function to solve the problem.
38+
}
39+
};

0 commit comments

Comments
 (0)