42. Number of Longest Increasing Subsequence

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 longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5.

Solution: (Using LIS and Count)

class Solution
{
public:
    int findNumberOfLIS(vector<int> &nums)
    {
        int n = nums.size();

        vector<int> dp(n, 1);
        vector<int> count(n, 1);

        int res = 1;

        for (int i = 1; i < n; i++)
        {

            for (int j = 0; j < i; j++)
            {
                if (nums[j] < nums[i] && dp[j] >= dp[i])
                {
                    dp[i] = max(dp[i], dp[j] + 1);
                     count[i] = count[j];
                }
                else if (nums[j] < nums[i] && dp[j] + 1 == dp[i])
                {
                    dp[i] = max(dp[i], dp[j] + 1);
                    count[i] += count[j];
                }
            }

            res = max(res, dp[i]);
        }

        int ct = 0;
        for (int i = 0; i < n; i++)
        {
            
            if (dp[i] == res)
            {
                ct += count[i];
            }
        }

        return ct;
    }
};

Time Complexity: O(n^2)

Last updated