algoadvance

Leetcode 673. Number of Longest Increasing Subsequence

Problem Statement

Given an unsorted array of integers nums, return the number of longest increasing subsequences.

Example:

Clarifying Questions

  1. What should be returned if the input array is empty?
    • If nums is empty, the number of longest increasing subsequences is 0.
  2. What is the range of values for the input array?
    • The problem does not specify any range constraints; we assume typical integer values are used.
  3. Can elements in the array be negative?
    • Yes, elements can be any integers, including negative values.

Strategy

To solve this problem, we’ll use dynamic programming with the following steps:

  1. Initial Setup:
    • Create two arrays: lengths and counts. lengths[i] will hold the length of the longest increasing subsequence that ends with nums[i]. counts[i] will hold the number of such subsequences ending at nums[i].
  2. Populate the Arrays:
    • Iterate through each element from left to right. For each element nums[i], iterate through all previous elements nums[j] (where j < i).
    • If nums[i] > nums[j], it means nums[i] can extend the subsequence ending at nums[j].
    • Depending on the length of subsequences, update lengths[i] and counts[i].
  3. Derive the Result:
    • Identify the maximum length from the lengths array.
    • Sum up all the counts corresponding to this maximum length.

Code

public class Solution {
    public int findNumberOfLIS(int[] nums) {
        if (nums.length == 0) return 0;

        int n = nums.length;
        int[] lengths = new int[n];
        int[] counts = new int[n];

        Arrays.fill(lengths, 1);
        Arrays.fill(counts, 1);

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j]) {
                    if (lengths[j] + 1 > lengths[i]) {
                        lengths[i] = lengths[j] + 1;
                        counts[i] = counts[j];
                    } else if (lengths[j] + 1 == lengths[i]) {
                        counts[i] += counts[j];
                    }
                }
            }
        }

        int maxLength = 0;
        for (int length : lengths) {
            maxLength = Math.max(maxLength, length);
        }

        int result = 0;
        for (int i = 0; i < n; i++) {
            if (lengths[i] == maxLength) {
                result += counts[i];
            }
        }

        return result;
    }
}

Time Complexity

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI