AlgoMaster Logo

Longest Increasing Subsequence

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Dynamic Programming

Intuition:

The idea is to use a dynamic programming table to keep track of the length of the longest increasing subsequence that ends with the element at each position in the array. At each element, we consider all previous elements and find the longest subsequence that this element can extend.

Steps:

  1. Initialize a dp array where dp[i] represents the length of the longest increasing subsequence that ends at index i.
  2. Iterate over each element in the array. For each element, check all previous elements:
    • If the current element is greater than the previous element, then it can extend the subsequence ending at that previous element.
    • Update dp[i] to be the maximum of its current value or dp[j] + 1 where j is an index before i.
  3. The answer is the maximum value in the dp array.

Code:

Intuition:

Instead of maintaining an array to find the longest increasing subsequence with a direct comparison which results in O(n^2) complexity, we can use a clever trick involving binary search. The approach is to maintain an array that keeps the "minimal" possible tail for all increasing subsequences of various lengths. This makes the time complexity significantly better.

Steps:

  1. Create an array tails where tails[i] represents the smallest tail value of all increasing subsequences of length i+1.
  2. For each number in the input array:
    • Use binary search (or manual iteration) to find the location it can replace in the tails array.
    • Update the tails array: if the number is larger than the largest element in tails, append it.
  3. The length of tails will be the length of the longest increasing subsequence.

Code: