Tutorialspoint
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)
ArraysDynamic Programming PwCSnowflake
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Create a DP array of the same length as the input array, initialized with 1 (as each element is an increasing subsequence of length 1).
 Step 2: For each element at position i, look back at all elements at positions j < i.
 Step 3: If nums[i] > nums[j], then the element at position i can be appended to the increasing subsequence ending at position j.
 Step 4: Update dp[i] to be the maximum of its current value and dp[j] + 1.
 Step 5: After filling the entire dp array, find the maximum value in it, which represents the length of the longest increasing subsequence.
 Step 6: For the optimized O(n log n) solution, maintain a sorted subsequence and use binary search to find the correct position to place each element.
 Step 7: The length of this list at the end gives the length of the LIS.

Submitted Code :