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)
assert Solution().findNumberOfLIS([1, 3, 5, 4, 7]) == 2
assert Solution().findNumberOfLIS([2, 2, 2, 2, 2]) == 5
class Solution {
public int findNumberOfLIS(int[] nums) {
int n = nums.length, best = 0, res = 0;
int[] len = new int[n], cnt = new int[n];
for (int i = 0; i < n; i++) {
len[i] = cnt[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[j] >= nums[i]) continue;
if (len[j] + 1 > len[i]) { len[i] = len[j] + 1; cnt[i] = cnt[j]; }
else if (len[j] + 1 == len[i]) cnt[i] += cnt[j];
}
if (len[i] > best) { best = len[i]; res = cnt[i]; }
else if (len[i] == best) res += cnt[i];
}
return res;
}
}
func findNumberOfLIS(nums []int) int {
n := len(nums)
length, cnt := make([]int, n), make([]int, n) // LIS length ending at i, and how many
best := 0
for i := 0; i < n; i++ {
length[i], cnt[i] = 1, 1
for j := 0; j < i; j++ {
if nums[j] < nums[i] {
if length[j]+1 > length[i] {
length[i], cnt[i] = length[j]+1, cnt[j]
} else if length[j]+1 == length[i] {
cnt[i] += cnt[j]
}
}
}
best = max(best, length[i])
}
total := 0
for i := range nums {
if length[i] == best {
total += cnt[i]
}
}
return total
}