Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Dynamic programming

How many longest increasing subsequences

Medium · Target 25 minutes · Dynamic programming · Type asked atGoogleAmazon

Given a list of integers nums, return the number of longest strictly increasing subsequences. Subsequences that use different positions count separately even if their values are equal.

Examples

InputOutputWhy
nums = [1,3,5,4,7]21, 3, 4, 7 and 1, 3, 5, 7.
nums = [2,2,2,2,2]5The longest has length 1, and there are five of them.
nums = [1,1,2,2]4Each 1 with each 2.

Constraints

  • 1 ≤ nums.length ≤ 2000
  • −10⁶ ≤ nums[i] ≤ 10⁶
  • The answer fits in a 32-bit integer

Hints

Hint 1

Keep two arrays: len[i], the longest increasing subsequence ending at i, and cnt[i], how many achieve that length.

Hint 2

For j < i with nums[j] < nums[i]: if len[j] + 1 is longer, take it and copy cnt[j]; if equal, add cnt[j].

Hint 3

Finally add cnt[i] over all i whose len[i] equals the overall maximum.

Where people lose marks

  • Adding counts for every compatible j rather than only those achieving the best length.
  • Returning the count at the last position instead of summing over all positions of maximum length.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.