Problem Description
Given an integer array nums, return the number of longest strictly increasing subsequences in the array. Note that the subsequence does not have to be contiguous.
Key Insights
- Use dynamic programming to keep track of both the length of the longest increasing subsequence (LIS) ending at each index and the number of ways to achieve that length.
- Maintain two arrays: one (dp) for the length of the LIS ending at the current index, and another (count) for the number of such LIS ending at that index.
- For each element, iterate over all previous elements; if a previous element is less than the current one, update the dp and count arrays.
- After processing, the result is the sum of counts for indices where the dp value equals the maximum length found.
Space and Time Complexity
Time Complexity: O(n²)
Space Complexity: O(n)
Solution
The solution uses dynamic programming with two auxiliary arrays. The dp array stores the length of the longest increasing subsequence ending at each index. The count array stores the number of ways to achieve that length at each index.
For every index i, loop through all previous indices j. If nums[j] is less than nums[i], meaning an increasing sequence can be formed:
- If extending the sequence from j gives a longer subsequence than previously recorded for i (i.e., dp[j] + 1 > dp[i]), update dp[i] and set count[i] equal to count[j].
- If it equals the already found length (i.e., dp[j] + 1 == dp[i]), then add count[j] to count[i] because another sequence of the same length is found.
Finally, the answer is computed by summing all count[i] for which dp[i] equals the maximum value in dp.