Leetcode 673. Number of Longest Increasing Subsequence
You are given an integer array nums
of size n
. Return the number of longest increasing subsequences.
Example:
Input: nums = [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 5, 7] and [1, 3, 4, 7].
n
?
nums
be negative?
nums
values, so we assume they can be any integers.nums
is empty?
nums
will not be empty.length[i]
will store the length of the longest increasing subsequence that ends in nums[i]
.count[i]
will store the number of longest increasing subsequences that end in nums[i]
.length
and count
arrays with 1s, since every element can be a subsequence of length 1 by itself.length
and count
arrays.(i, j)
such that i > j
and nums[i] > nums[j]
:
length[j] + 1 > length[i]
, update length[i]
and set count[i] = count[j]
.length[j] + 1 == length[i]
, increment count[i]
by count[j]
.length
array indicates the length of the longest increasing subsequence.count
array for indices where the length
matches the maximum length.O(n^2)
where n
is the length of nums
, due to the nested loops iterating over each pair (i, j)
.#include <vector>
#include <algorithm>
int findNumberOfLIS(std::vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
std::vector<int> length(n, 1); // length[i] -> length of LIS ending at index i
std::vector<int> count(n, 1); // count[i] -> number of LIS ending at index i
for (int i = 1; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[i] > nums[j]) {
if (length[j] + 1 > length[i]) {
length[i] = length[j] + 1;
count[i] = count[j];
} else if (length[j] + 1 == length[i]) {
count[i] += count[j];
}
}
}
}
int longest = *std::max_element(length.begin(), length.end());
int result = 0;
for (int i = 0; i < n; ++i) {
if (length[i] == longest) {
result += count[i];
}
}
return result;
}
This code correctly finds the number of longest increasing subsequences in a given array nums
using a dynamic programming approach. Make sure to test it with various edge cases to ensure its correctness and efficiency.
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?