Number of Longest Increasing Subsequences

Dynamic Programming LIS Easy

Given an integer array nums, find the number of Longest Increasing Subsequences (LIS) in the array.

Examples:

Input: nums = [1, 3, 5, 4, 7]

Output: 2

Explanation: There are two LIS of length 4:

[1, 3, 4, 7]

[1, 3, 5, 7].

Input: nums = [2, 2, 2, 2, 2]

Output: 5

Explanation: All elements are the same, so every single element can form an LIS of length 1. There are 5 such subsequences.

Input: nums = [10, 9, 2, 5, 3, 7, 101, 18]

Constraints

  • 1 <= nums.length <= 103
  • -106 <= nums[i] <= 106

Hints

  • "We solve this using Dynamic Programming (DP) with two arrays: dp[i] → The length of the longest increasing subsequence ending at index i. count[i] → The number of LIS ending at index i."
  • "For each index i, iterate over all j < i: If nums[j] < nums[i]: If dp[j] + 1 > dp[i], update dp[i] and reset count[i] = count[j]. If dp[j] + 1 == dp[i], add count[j] to count[i]. Finally, sum up all count[i] where dp[i] equals the maximum LIS length."