You are given an integer array nums. A subsequence keeps some of the numbers in their original order, possibly skipping others. It is increasing when each number is strictly bigger than the one before it.
Find the greatest length an increasing subsequence can have, and return how many increasing subsequences have exactly that length. Two subsequences are different if they use a different set of positions.
Example 1
Input: nums = [2, 6, 4, 8, 7] Output: 4 Why: 2,6,8 / 2,6,7 / 2,4,8 / 2,4,7 all have length 3
2 more examples and the constraints
Example 2
Input: nums = [5, 5, 5] Output: 3 Why: the longest length is 1, and any single 5 works
Example 3
Input: nums = [9, 1, 3, 2] Output: 2 Why: 1, 3 and 1, 2 are the two of length 2
Constraints
- 1 ≤ length of nums ≤ 2,000
- Every number is between −1,000,000 and 1,000,000
- The answer fits in a 32-bit signed integer
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- DP over every earlier indexO(n²)
- Fenwick tree over value ranksO(n log n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 2,000 numbers | Verdict |
|---|---|---|---|
| DP over every earlier index | O(n²) | Passes; the expected answer | |
| Fenwick tree over value ranks | O(n log n) | Best; scales to large inputs |
n = length of nums.
Edge cases to test
- All values equal. [5, 5, 5] gives 3: each single number is a longest run.
- One number. [7] gives 1.
- Strictly rising. [1, 2, 3, 4] has one longest run, so the answer is 1.
- Strictly falling. [5, 4, 3, 2, 1] gives 5, one run per number.
- Counts that double. [2, 1, 4, 3, 6, 5, ...] doubles the count with each pair; 60 numbers give 2^30.
Common mistakes
- Counting only the runs that end at the last index instead of every index with the longest length.
- Setting count[i] = count[j] on a tie, which throws away the ways already found.
- Allowing equal values to extend a run; the subsequence must be strictly increasing.
How to talk through it
- 1Clarify. Strictly increasing? Do different positions with equal values count as different subsequences?
- 2Start from LIS. The O(n²) LIS DP gives the length; add a count array beside it.
- 3State the update. Longer: replace length and copy the count. Equal: add the count.
- 4Speed it up if asked. The inner loop is a prefix query over values, so a Fenwick tree of (length, count) pairs makes it O(n log n).
- 5Test out loud. Run all equal values, a falling list and Example 1.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?