712383. Number of Longest Increasing Subsequence

Medium

Here is the detailed Markdown blog post for the problem:

Number of Longest Increasing Subsequence

Summary

Given an array of integers, find the number of longest increasing subsequences (LIS) in the array. A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.

The key concept involved is dynamic programming.

Detailed Explanation

To solve this problem, we will use dynamic programming to find the number of longest increasing subsequences (LIS) in the array. The idea is to create a 2D array dp where dp[i][j] represents whether there exists an increasing subsequence with length j ending at index i.

Here's the step-by-step breakdown:

  1. Initialize a 2D array dp of size (n x (max + 1)), where n is the length of the input array and max is the maximum value in the array.
  2. Iterate through the array from left to right:
    • For each element at index i, iterate from j = 1 to max:
      • Check if there exists an increasing subsequence with length j-1 ending at index i-1. If yes, and the current element is greater than or equal to the last element of that subsequence, then update dp[i][j] to dp[i-1][j-1] + 1.
      • If no such subsequence exists, set dp[i][j] = 0.
  3. The value at dp[n-1][max] represents the number of longest increasing subsequences (LIS) in the array.

Time complexity: O(n * max) Space complexity: O(n * max)

Optimized Solutions

Java

View on GeeksforGeeks
public int findNumberLongestIncreasingSubsequence(int[] arr) {
    int n = arr.length;
    int max = Arrays.stream(arr).max().getAsInt();
    int[][] dp = new int[n][max + 1];
    
    for (int i = 0; i < n; i++) {
        for (int j = 1; j <= max; j++) {
            if (i == 0 || arr[i] >= arr[i-1]) {
                dp[i][j] = (dp[i-1][j-1] > 0) ? dp[i-1][j-1] + 1 : 0;
            } else {
                dp[i][j] = 0;
            }
        }
    }
    
    return dp[n-1][max];
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.