LeetCode 354: Russian Doll Envelopes Solution
Master LeetCode problem 354 (Russian Doll Envelopes), 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.
354. Russian Doll Envelopes
Problem Explanation
Explanation:
To solve this problem, we can follow these steps:
- Sort the envelopes based on their widths in ascending order. If two envelopes have the same width, sort them based on their heights in descending order.
- Apply Longest Increasing Subsequence (LIS) algorithm on the heights of the envelopes.
- The length of the LIS will give us the maximum number of envelopes we can Russian doll.
Time complexity: O(nlogn) where n is the number of envelopes. Sorting the envelopes takes O(nlogn) time, and finding the LIS takes O(nlogn) time. Space complexity: O(n) for storing the sorted envelopes and LIS array.
:
Solution Code
class Solution {
public int maxEnvelopes(int[][] envelopes) {
Arrays.sort(envelopes, (a, b) -> a[0] == b[0] ? b[1] - a[1] : a[0] - b[0]);
int n = envelopes.length;
int[] dp = new int[n];
Arrays.fill(dp, 1);
int maxEnvelopes = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (envelopes[i][1] > envelopes[j][1]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
maxEnvelopes = Math.max(maxEnvelopes, dp[i]);
}
return maxEnvelopes;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 354 (Russian Doll Envelopes)?
This page provides optimized solutions for LeetCode problem 354 (Russian Doll Envelopes) 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 354 (Russian Doll Envelopes)?
The time complexity for LeetCode 354 (Russian Doll Envelopes) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 354 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 354 in Java, C++, or Python.