Skip to content

Commit 1f0e17e

Browse files
committed
Longest Increasing subsequence using binary search most optimal approach for this problem
1 parent c1b18f1 commit 1f0e17e

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

search/Longest_Increasing_Subsequence_using_binary_search.cpp

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
/**
32
* @file
43
* @brief find the length of the Longest Increasing Subsequence (LIS)
@@ -53,27 +52,31 @@
5352
#include <iostream> /// for IO operations
5453
#include <vector> /// for std::vector
5554
#include <algorithm> /// for std::lower_bound
55+
#include <cstdint> /// for std::uint32_t
5656

5757
/**
5858
* @brief Function to find the length of the Longest Increasing Subsequence (LIS)
5959
* using Binary Search
60-
* @param nums The input vector of integers
60+
* @tparam T The type of the elements in the input vector
61+
* @param nums The input vector of elements of type T
6162
* @return The length of the longest increasing subsequence
6263
*/
63-
int longest_increasing_subsequence_using_binary_search(std::vector<int>& nums) {
64+
65+
template <typename T>
66+
std::uint32_t longest_increasing_subsequence_using_binary_search(std::vector<T>& nums) {
6467
if (nums.empty()) return 0;
6568

66-
std::vector<int> ans;
69+
std::vector<T> ans;
6770
ans.push_back(nums[0]);
68-
for (int i = 1; i < nums.size(); i++) {
71+
for (std::size_t i = 1; i < nums.size(); i++) {
6972
if (nums[i] > ans.back()) {
7073
ans.push_back(nums[i]);
7174
} else {
72-
int idx = std::lower_bound(ans.begin(), ans.end(), nums[i]) - ans.begin();
75+
auto idx = std::lower_bound(ans.begin(), ans.end(), nums[i]) - ans.begin();
7376
ans[idx] = nums[i];
7477
}
7578
}
76-
return ans.size();
79+
return static_cast<std::uint32_t>(ans.size());
7780
}
7881

7982
/**
@@ -93,8 +96,14 @@ static void tests() {
9396
std::vector<int> arr4 = {-10, -1, -5, 0, 5, 1, 2};
9497
assert(longest_increasing_subsequence_using_binary_search(arr4) == 5);
9598

96-
std::vector<int> arr5 = {};
97-
assert(longest_increasing_subsequence_using_binary_search(arr5) == 0);
99+
std::vector<double> arr5 = {3.5, 1.2, 2.8, 3.1, 4.0};
100+
assert(longest_increasing_subsequence_using_binary_search(arr5) == 4);
101+
102+
std::vector<char> arr6 = {'a', 'b', 'c', 'a', 'd'};
103+
assert(longest_increasing_subsequence_using_binary_search(arr6) == 4);
104+
105+
std::vector<int> arr7 = {};
106+
assert(longest_increasing_subsequence_using_binary_search(arr7) == 0);
98107

99108
std::cout << "All tests have successfully passed!\n";
100109
}

0 commit comments

Comments
 (0)