Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 300 Longest Increasing Subsequence - Walkthrough

Tracing the O(n^2) algorithm

Trace LIS on [10,9,2,5,3,7,101,18][10, 9, 2, 5, 3, 7, 101, 18]. Let dp[i]dp[i] = length of LIS ending at ii. dp[0]=1dp[0] = 1 (just 1010). dp[1]=1dp[1] = 1 (just 99, can't extend from 1010). dp[2]=1dp[2] = 1 (just 22). dp[3]=2dp[3] = 2 (extend from 22: [2,5][2, 5]). dp[4]=2dp[4] = 2 (extend from 22: [2,3][2, 3]). dp[5]=3dp[5] = 3 (extend from 55 or 33: [2,5,7][2, 5, 7]). dp[6]=4dp[6] = 4 (extend from 77: [2,5,7,101][2, 5, 7, 101]). dp[7]=4dp[7] = 4 (extend from 77: [2,5,7,18][2, 5, 7, 18]).

Answer: max(dp)=4\max(dp) = 4.