From da488ed2074a50cd77224061a2c4101847094786 Mon Sep 17 00:00:00 2001 From: Div Date: Mon, 13 Oct 2025 02:17:58 +0530 Subject: [PATCH] Create longest_increasing_subsequence.cpp // Longest Increasing Subsequence (LeetCode #300) // Finds the length of the longest strictly increasing subsequence in an array. // Implemented using O(n log n) approach with binary search (std::lower_bound). // Beginner-friendly C++ project for Hacktoberfest 2025. --- longest_increasing_subsequence.cpp | 34 ++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 longest_increasing_subsequence.cpp 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; +}