Editorial for Longest Increasing Subsequence


Approach

Let dpidp_i be the length of the longest increasing subsequence that ends exactly at position ii.

For each earlier position j<ij < i, if aj<aia_j < a_i, then we can append aia_i after a subsequence ending at jj. Therefore, dpidp_i is one more than the maximum valid dpjdp_j, or 11 if no earlier value can come before aia_i.

The answer is the maximum value among all dpidp_i. Equal values cannot extend each other because the subsequence must be strictly increasing.

Time complexity is O(n2)O(n^2).

Solution (Python)

Code 1
n = int(input())
a = list(map(int, input().split()))

dp = [1] * n
answer = 1

for i in range(n):
    best = 1
    ai = a[i]
    for j in range(i):
        if a[j] < ai:
            best = max(best, dp[j] + 1)
    dp[i] = best
    answer = max(answer, best)

print(answer)

Comments0


No comments yet

Be the first to comment.

New comment


Log in to join the discussion.