LeetCode 673: Number of Longest Increasing Subsequence Solution
Master LeetCode problem 673 (Number of Longest Increasing Subsequence), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
673. Number of Longest Increasing Subsequence
Problem Explanation
Explanation:
To solve this problem, we can use dynamic programming. We will maintain two arrays lengths and counts. The lengths[i] will store the length of the longest increasing subsequence ending at index i, and counts[i] will store the number of such subsequences ending at index i.
We iterate through the array nums and for each element at index i, we iterate from 0 to i-1 to find the longest increasing subsequence ending at index i. If nums[i] > nums[j], we update lengths[i] and counts[i] based on the values of lengths[j] and counts[j]. If lengths[j] + 1 > lengths[i], we update both lengths[i] and counts[i]. If lengths[j] + 1 == lengths[i], we increment counts[i] by counts[j].
Finally, we find the maximum length of the longest increasing subsequence in the lengths array and sum up the corresponding counts in the counts array.
Time Complexity: O(n^2) where n is the length of the input array nums.
Space Complexity: O(n) where n is the length of the input array nums.
:
Solution Code
class Solution {
public int findNumberOfLIS(int[] nums) {
int n = nums.length;
int[] lengths = new int[n];
int[] counts = new int[n];
Arrays.fill(lengths, 1);
Arrays.fill(counts, 1);
int maxLength = 1;
int result = 0;
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];
}
}
}
maxLength = Math.max(maxLength, lengths[i]);
}
for (int i = 0; i < n; i++) {
if (lengths[i] == maxLength) {
result += counts[i];
}
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 673 (Number of Longest Increasing Subsequence)?
This page provides optimized solutions for LeetCode problem 673 (Number of Longest Increasing Subsequence) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 673 (Number of Longest Increasing Subsequence)?
The time complexity for LeetCode 673 (Number of Longest Increasing Subsequence) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 673 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 673 in Java, C++, or Python.