Number of Longest Increasing Subsequence

Given an unsorted array of integers, find the number of longest increasing subsequence.

Example 1:

Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].

Example 2:

Input: [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.

Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int.

class Solution {
    public int findNumberOfLIS(int[] nums) {
        if (nums.length == 0)
            return 0;
        int dp[] = new int[nums.length];
        int count[] = new int[nums.length];
        int max = 1;
        dp[0] = 1;
        count[0] = 1;
        // dp[i] -> length of LIS upto this point(including this point)
        for (int i = 1; i < nums.length; i++) {
            dp[i] = 1;// base case
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) // For increasing subsequence
                    dp[i] = Math.max(dp[i], dp[j] + 1);
            }
            max = Math.max(dp[i], max);
            if (dp[i] == 1)
                count[i] = 1;
            else {
                for (int j = 0; j < i; j++) {
                    if (nums[j] < nums[i] && dp[i] == dp[j] + 1)
                        count[i] += count[j];
                }
            }
        }
        int ans = 0;
        for (int i = 0; i < dp.length; i++) {
            if (max == dp[i]) {
                ans += count[i];
            }
        }
        return ans;
    }
}

Last updated