LeetCode 2407: Longest Increasing Subsequence II Solution
Master LeetCode problem 2407 (Longest Increasing Subsequence II), a hard 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.
2407. Longest Increasing Subsequence II
Problem Explanation
Explanation:
To solve this problem, we can use dynamic programming to find the longest increasing subsequence with a maximum difference of k between adjacent elements. The idea is to maintain a list of the longest increasing subsequences ending at each index of the input array. For each index, we can iterate through all previous elements to find the longest increasing subsequence that ends with that element and also satisfies the maximum difference constraint.
Algorithm:
- Initialize a dynamic programming array
dpof length equal to the input arraynums. - For each index
iin the arraynums, iterate from indexj=0toi-1:- If
nums[i] - nums[j] <= k, updatedp[i]to the maximum ofdp[i]anddp[j] + 1.
- If
- Find the maximum value in the
dparray which represents the length of the longest increasing subsequence that satisfies the maximum difference constraint. - Return the maximum value as the result.
Time Complexity:
The time complexity of this approach is O(n^2), where n is the length of the input array nums.
Space Complexity:
The space complexity is O(n) to store the dynamic programming array.
:
Solution Code
class Solution {
public int lengthOfLIS(int[] nums, int k) {
int n = nums.length;
int[] dp = new int[n];
Arrays.fill(dp, 1);
int maxLen = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] - nums[j] <= k) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
maxLen = Math.max(maxLen, dp[i]);
}
return maxLen;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2407 (Longest Increasing Subsequence II)?
This page provides optimized solutions for LeetCode problem 2407 (Longest Increasing Subsequence II) 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 2407 (Longest Increasing Subsequence II)?
The time complexity for LeetCode 2407 (Longest Increasing Subsequence II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2407 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2407 in Java, C++, or Python.