Editorial for Longest Increasing Subsequence
Use this editorial only when stuck, and do not 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.
Approach
Let dpi be the length of the longest increasing subsequence that ends exactly at position i.
For each earlier position j<i, if aj<ai, then we can append ai after a subsequence ending at j. Therefore, dpi is one more than the maximum valid dpj, or 1 if no earlier value can come before ai.
The answer is the maximum value among all dpi. Equal values cannot extend each other because the subsequence must be strictly increasing.
Time complexity is O(n2).
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)
Comments0
No comments yet
Be the first to comment.
New comment
Log in to join the discussion.