TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
longest_increasing_subsequence_using_binary_search.cpp
Go to the documentation of this file.
1
51#include <cassert>
52#include <iostream>
53#include <vector>
54#include <algorithm>
55#include <cstdint>
56
64template <typename T>
65std::uint32_t longest_increasing_subsequence_using_binary_search(std::vector<T>& nums) {
66 if (nums.empty()) return 0;
67
68 std::vector<T> ans;
69 ans.push_back(nums[0]);
70 for (std::size_t i = 1; i < nums.size(); i++) {
71 if (nums[i] > ans.back()) {
72 ans.push_back(nums[i]);
73 } else {
74 auto idx = std::lower_bound(ans.begin(), ans.end(), nums[i]) - ans.begin();
75 ans[idx] = nums[i];
76 }
77 }
78 return static_cast<std::uint32_t>(ans.size());
79}
80
85static void tests() {
86 std::vector<int> arr = {10, 9, 2, 5, 3, 7, 101, 18};
88
89 std::vector<int> arr2 = {0, 1, 0, 3, 2, 3};
91
92 std::vector<int> arr3 = {7, 7, 7, 7, 7, 7, 7};
94
95 std::vector<int> arr4 = {-10, -1, -5, 0, 5, 1, 2};
97
98 std::vector<double> arr5 = {3.5, 1.2, 2.8, 3.1, 4.0};
100
101 std::vector<char> arr6 = {'a', 'b', 'c', 'a', 'd'};
103
104 std::vector<int> arr7 = {};
106
107 std::cout << "All tests have successfully passed!\n";
108}
109
114int main() {
115 tests(); // run self test implementation
116 return 0;
117}
std::uint32_t longest_increasing_subsequence_using_binary_search(std::vector< T > &nums)
for std::uint32_t
static void tests()
Test cases for Longest Increasing Subsequence function.
int main()
Main function to run tests.