Leetcode 673. Number of Longest Increasing Subsequence
Given an unsorted array of integers nums
, return the number of longest increasing subsequences.
Example:
nums = [1,3,5,4,7]
2
[1, 3, 4, 7]
and [1, 3, 5, 7]
.nums = [2,2,2,2,2]
5
1
, and there are 5
increasing subsequences of length 1
, so the answer is 5
.nums
is empty, the number of longest increasing subsequences is 0
.To solve this problem, we’ll use dynamic programming with the following steps:
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]
.nums[i]
, iterate through all previous elements nums[j]
(where j < i
).nums[i] > nums[j]
, it means nums[i]
can extend the subsequence ending at nums[j]
.lengths[i]
and counts[i]
.lengths
array.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;
}
}
lengths
and counts
arrays.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?