Tutorialspoint
Problem
Solution
Submissions

Longest Increasing Subsequence

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 10

Write a C program to find the length of the longest increasing subsequence in an array. A longest increasing subsequence is a subsequence of a sequence in which the subsequence's elements are in sorted order, lowest to highest, and in which the subsequence is as long as possible. Note that the elements don't have to be consecutive in the original array.

Example 1
  • Input: arr = [10, 9, 2, 5, 3, 7, 101, 18]
  • Output: 4
  • Explanation:
    • Step 1: The longest increasing subsequence is [2, 3, 7, 18].
    • Step 2: Other possible increasing subsequences are [2, 3, 7], [2, 5, 7], etc.
    • Step 3: The length of the longest one is 4.
Example 2
  • Input: arr = [0, 1, 0, 3, 2, 3]
  • Output: 4
  • Explanation:
    • Step 1: The longest increasing subsequence is [0, 1, 2, 3].
    • Step 2: Another possible subsequence is [0, 1, 3].
    • Step 3: The maximum length is 4.
Constraints
  • 1 ≤ arr.length ≤ 2500
  • -10^4 ≤ arr[i] ≤ 10^4
  • Time Complexity: O(n^2)
  • Space Complexity: O(n)
ArraysDynamic Programming DeloitteDropbox
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

  • Use dynamic programming approach to solve this problem.
  • Create a dp array where dp[i] represents the length of LIS ending at index i.
  • Initialize all dp values to 1 (each element forms a subsequence of length 1).
  • For each element, check all previous elements and update dp[i] accordingly.
  • The answer will be the maximum value in the dp array.

Steps to solve by this approach:

 Step 1: Create a dp array where dp[i] represents the length of LIS ending at index i.
 Step 2: Initialize all dp values to 1 since each element forms a subsequence of length 1.
 Step 3: For each element at index i, check all previous elements (j < i).
 Step 4: If nums[i] > nums[j], update dp[i] = max(dp[i], dp[j] + 1).
 Step 5: Continue this process for all elements in the array.
 Step 6: Find the maximum value in the dp array which represents the length of LIS.
 Step 7: Return the maximum length found.

Submitted Code :