Editorial for Longest Increasing Subsequence
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
Approach
Let be the length of the longest increasing subsequence that ends exactly at position
.
For each earlier position , if
, then we can append
after a subsequence
ending at
. Therefore,
is one more than the maximum valid
, or
if no earlier
value can come before
.
The answer is the maximum value among all . Equal values cannot extend each other because
the subsequence must be strictly increasing.
Time complexity is .
Solution (Python)
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)
Comments