awelgorithms

LIS in quadratic time

Updated

dp[i] = length of LIS ending at i. dp[i] = 1 + max{dp[j] : j<i and a[j]<a[i]}, or 1 if no such j. Answer is max(dp). Two nested loops, O(n²).

What to focus on

Ending at i is required so the compare a[j]<a[i] is legal. A 1D 'best so far' without the ending index cannot test the increase. Strict < unless the spec allows equals.

Worked examples

two increasing pairs

a = [4, 1, 9]
  1. dp[0]=1
  2. dp[1]=1 (1<4 but 1 is later)
  3. dp[2]=1+max(1,1)=2

Result: LIS 2

fully increasing

a = [1, 4, 9]
  1. dp[0]=1
  2. dp[1]=2
  3. dp[2]=3

Result: LIS 3

singleton

a = [4]
  1. no j<i

Result: LIS 1

Try it

Write lis(a). a is an array of integers. dp[i] is the length of the LIS ending at i. LIS uses strict increase. Return max(dp). [4, 1, 9] → 2. [1, 4, 9] → 3. [4] → 1.

a is a non-empty array of integers. n ≥ 1. LIS uses strict increase.