Number of Longest Increasing Subsequence⚓︎
Description⚓︎
Given an integer array nums, return the number of longest increasing subsequences.
Notice that the sequence has to be strictly increasing.
Example 1:
- Input:
nums = [1,3,5,4,7] - Output:
2 - Explanation:
The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
- Input:
nums = [2,2,2,2,2] - Output:
5 - Explanation:
The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.
Constraints:
1 <= nums.length <= 2000-10^6 <= nums[i] <= 10^6
Solution⚓︎
- Time complexity: \(O(n^2)\);
- Space complexity: \(O(n)\).
Variables:
dp[i]: The length of the longest increasing subsequence ending at indexi.count[i]: The number of longest increasing subsequences ending at indexi.
Logic:
- We iterate over each element
nums[i]in the array. - For each
nums[i], we check all previous elementsnums[j](j < i). - If
nums[i]is greater thannums[j], it meansnums[i]can extend the increasing subsequence ending atnums[j]. - We then update
dp[i]andcount[i]based on the conditions:- If the length of the increasing subsequence ending at
nums[j]plus 1 (dp[j] + 1) is greater than the currentdp[i], we found a longer subsequence ending ati, so we updatedp[i]and setcount[i]tocount[j]. - If
dp[j] + 1is equal todp[i], it means we found another subsequence of the same length as the longest found so far, so we addcount[j]tocount[i].
- If the length of the increasing subsequence ending at
- Finally, we find the length of the longest increasing subsequence (
maxVal) and sum up allcount[i]wheredp[i]is equal tomaxVal.
State Transformation Equations:
dp[i] = max(dp[i], dp[j] + 1)for allj < iandnums[i] > nums[j].count[i]is updated as follows:count[i] = count[j]ifdp[j] + 1 > dp[i].count[i] += count[j]ifdp[j] + 1 == dp[i].