From cdc93a3550846e7979f4d535ee9bd4fecbbd07b4 Mon Sep 17 00:00:00 2001 From: Hitesh Kumar <51043123+hiteshskp@users.noreply.github.com> Date: Sat, 3 May 2025 17:01:39 +0530 Subject: [PATCH] Update number-of-longest-increasing-subsequence.py --- ...umber-of-longest-increasing-subsequence.py | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/Python/number-of-longest-increasing-subsequence.py b/Python/number-of-longest-increasing-subsequence.py index 2cb120346a..d32b0a3068 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)