AlgoMaster Logo

Number of Longest Increasing Subsequence

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Dynamic Programming with Two Arrays

Intuition:

The problem is to find the number of longest increasing subsequences in the given array. Here, we will use a dynamic programming approach where one array will keep track of the length of the longest increasing subsequence ending at each index, and another array will keep the number of such subsequences.

Steps:

  1. Create two arrays: lengths and counts.
    • lengths[i] will store the length of the longest increasing subsequence ending at index i.
    • counts[i] will store the number of longest increasing subsequences ending at index i.
  2. Initialize each element of lengths to 1 because the minimum length of an increasing subsequence ending at any element is 1 (the element itself).
  3. Initialize each element of counts to 1 because there's at least one subsequence ending at each element (the element itself).
  4. Iterate through the array with two nested loops:
    • For each pair of indices (j < i), check if nums[j] < nums[i].
    • If it is, update the lengths and counts arrays.
      • If lengths[j] + 1 > lengths[i], it means we have found a longer subsequence by adding nums[i] to the subsequence ending at nums[j]. Thus, update lengths[i] and set counts[i] = counts[j].
      • If lengths[j] + 1 == lengths[i], it means we have found another subsequence of the same maximum length. Add counts[j] to counts[i].
  5. After processing, find the maximum value in the lengths array, which represents the length of the longest increasing subsequence.
  6. Sum up all values in counts where corresponding lengths are equal to the maximum value found in step 5.

Code: