
Problem
Solution
Submissions
Longest Increasing Subsequence
Certification: Intermediate Level
Accuracy: 0%
Submissions: 1
Points: 15
Write a C++ program to find the Longest Increasing Subsequence (LIS) in an array. Given an integer array nums, implement a function lengthOfLIS(vector<int>& nums)
that returns the length of the longest strictly increasing subsequence. A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements.
Example 1
- Input: nums = [10, 9, 2, 5, 3, 7, 101, 18]
- Output: 4
- Explanation:
- The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4.
- Other possible increasing subsequences are [10, 101], [9, 101], [2, 5, 7, 101], etc., but none are longer than 4 elements.
Example 2
- Input: nums = [0, 1, 0, 3, 2, 3]
- Output: 4
- Explanation:
- The longest increasing subsequence is [0, 1, 2, 3], therefore the length is 4.
- Note that even though [0, 1, 0, 3] is an increasing subsequence, it's not the longest one.
Constraints
- 1 ≤ nums.length ≤ 2500
- -10^4 ≤ nums[i] ≤ 10^4
- Time Complexity: O(n²) for dynamic programming, O(n log n) for optimal solution
- Space Complexity: O(n)
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Dynamic programming can be used to solve this problem with O(n²) time complexity
- Create an array to store the length of LIS ending at each position
- For each element, find the longest subsequence that can be formed by including it
- An optimized solution using binary search can achieve O(n log n) time complexity
- For the optimized solution, maintain a list that represents the smallest element seen so far that ends an increasing subsequence of length i