Example 1
- Input
- nums = [3, 1, 2]
- Output
- 2
Skip 3 and keep indices 1 and 2, giving [1, 2]. Keeping 3 prevents either later pick, and the entire array is not increasing, so the maximum length is 2.
Given an integer array, find the length of the longest subsequence whose values rise strictly from left to right.
You are given an integer array nums. A subsequence keeps some elements in their original order while deleting the rest.
Return the length of the longest subsequence that is strictly increasing. The subsequence itself need not be contiguous, and equal values never extend a strictly rising run.
Skip 3 and keep indices 1 and 2, giving [1, 2]. Keeping 3 prevents either later pick, and the entire array is not increasing, so the maximum length is 2.
Indices 2, 4, 5 and 6 give [2, 3, 7, 101]; choosing index 7 instead of 6 also gives [2, 3, 7, 18]. A length-5 subsequence is impossible: after choosing 2, at most one of 5 and 3 can be kept, followed by 7 and at most one of 101 and 18.
Indices 0, 1, 4 and 5 give [0, 1, 2, 3]. The earlier 3 at index 3 must be skipped to use the later 2. Repeated 0 and 3 values cannot themselves extend a strictly increasing subsequence, so the answer is 4.
No pair of positions has a strictly larger second value. Every single 7 is valid, but adding another 7 would violate strict increase, so the answer is 1.
The sole negative value forms a subsequence of length 1. A starting sentinel of 0 would incorrectly forbid this value; an index of -1 represents no previous pick.
A subsequence may skip positions, but it must keep their order. In Example 1, keeping 3 blocks both later values, while skipping it lets us keep [1, 2]. Enumerating picks and skips discovers this length, but many branches ask the same future question. For a given length, a smaller final value is always at least as easy to extend: ending at 1 instead of 3 preserves the chance to use a later 2. The fast method remembers only that smallest tail for each possible length, rather than every subsequence.
Reveal Recursive Pick Or Skip: intuition, complexity, and code
[7, 7, 7] return 1 since rises must be strict.1; every value only replaces the length-1 tail.n.>= instead of > when extending lets equal values chain and overcounts runs like [2, 2].tails contents as the run itself; only its length is guaranteed, not its members.When subsequence length only cares about the best tail per length, maintain those tails in sorted order and place each element with binary search for a near-linear solution.