diff --git a/longest_increasing_subsequence.cpp b/longest_increasing_subsequence.cpp new file mode 100644 index 0000000..da2f7e3 --- /dev/null +++ b/longest_increasing_subsequence.cpp @@ -0,0 +1,34 @@ +#include +using namespace std; + +class Solution { +public: + int lengthOfLIS(vector& nums) { + vector sub; // stores the current increasing subsequence + for (int num : nums) { + auto it = lower_bound(sub.begin(), sub.end(), num); + if (it == sub.end()) { + sub.push_back(num); + } else { + *it = num; // replace to maintain lowest possible value + } + } + return sub.size(); + } +}; + +// Test Example +int main() { + Solution sol; + + vector nums1 = {10,9,2,5,3,7,101,18}; + cout << sol.lengthOfLIS(nums1) << endl; // Output: 4 + + vector nums2 = {0,1,0,3,2,3}; + cout << sol.lengthOfLIS(nums2) << endl; // Output: 4 + + vector nums3 = {7,7,7,7,7,7,7}; + cout << sol.lengthOfLIS(nums3) << endl; // Output: 1 + + return 0; +}