Input: nums =[1,3,5,4,7]Output: 2Explanation: The two longest increasing subsequences are [1,3,4,7] and [1,3,5,7].
Example 2:
1
2
3
Input: nums =[2,2,2,2,2]Output: 5Explanation: The length of longest continuous increasing subsequence is1, and there are 5 subsequences' length is1, so output 5.
We want to find not just the length of the longest increasing subsequence (LIS), but also how many such sequences exist. For each position, we track both the length of the LIS ending there and the number of ways to achieve that length. By updating these values as we iterate, we can efficiently count all LIS.
The approach uses two arrays, len[n] and cnt[n], to store the length of the longest increasing subsequence ending at nums[i] and the count of such sequences, respectively.
len[i]: Length of LIS ending at index i.
cnt[i]: Number of LIS ending at index i.
For each index i:
Set len[i] = 1 and cnt[i] = 1 (every element is an LIS of length 1).
For each previous index j < i:
If nums[i] > nums[j]:
If len[j] + 1 > len[i], update len[i] = len[j] + 1 and set cnt[i] = cnt[j].
If len[j] + 1 == len[i], increment cnt[i] by cnt[j].
Find the maximum value in len.
Sum all cnt[i] where len[i] equals the maximum length.
classSolution:
deffindNumberOfLIS(self, nums: list[int]) -> int:
n = len(nums)
if n ==0:
return0 length = [1] * n
count = [1] * n
mx =0 ans =0for i in range(n):
for j in range(i):
if nums[i] > nums[j]:
if length[j] +1> length[i]:
length[i] = length[j] +1 count[i] = count[j]
elif length[j] +1== length[i]:
count[i] += count[j]
if length[i] > mx:
mx = length[i]
ans = count[i]
elif length[i] == mx:
ans += count[i]
return ans