SDE & MLE Prep

673. Number of Longest Increasing Subsequence

Problem

Return how many longest strictly increasing subsequences nums has.

Example: [1,3,5,4,7] → 2 (1, 3, 4, 7 and 1, 3, 5, 7); [2,2,2,2,2] → 5

Constraints: n ≤ 2000.

Alongside len[i] (LIS ending at i) keep cnt[i] (how many). For j < i with nums[j] < nums[i]: a longer length resets the count; an equal length adds cnt[j].

Complexity: O(n²).

class Solution:
    def findNumberOfLIS(self, nums: List[int]) -> int:
        n = len(nums)
        length, cnt = [1] * n, [1] * n
        for i in range(n):
            for j in range(i):
                if nums[j] < nums[i]:
                    if length[j] + 1 > length[i]:
                        length[i], cnt[i] = length[j] + 1, cnt[j]
                    elif length[j] + 1 == length[i]:
                        cnt[i] += cnt[j]
        best = max(length)
        return sum(c for l, c in zip(length, cnt) if l == best)