diff --git a/Python/number-of-longest-increasing-subsequence.py b/Python/number-of-longest-increasing-subsequence.py index 2cb120346..d32b0a306 100644 --- a/Python/number-of-longest-increasing-subsequence.py +++ b/Python/number-of-longest-increasing-subsequence.py @@ -23,3 +23,24 @@ def findNumberOfLIS(self, nums): result = dp[i][1] return result +# Time: O(n^2) +# Space: O(n) +class Solution2: + def findNumberOfLIS(self, nums: List[int]) -> int: + n =len(nums) + if n == 0 : + return 0 + + lengths = [1] * n # lengths[i] = length of LIS ending at index i + counts = [1] * n # counts[i] = number of LIS ending at index i + + for i in range(n): + for j in range(i): + if nums[j] < nums[i]: + if lengths[j]+1 > lengths[i]: + lengths[i] = lengths[j]+1 + counts[i] = counts[j] + elif lengths[j] + 1 == lengths[i]: + counts[i] += counts[j] + max_len = max(lengths) + return sum(c for l, c in zip(lengths, counts) if l == max_len)