LeetCode 1691: Maximum Height by Stacking Cuboids Solution
Master LeetCode problem 1691 (Maximum Height by Stacking Cuboids ), 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.
1691. Maximum Height by Stacking Cuboids
Problem Explanation
Explanation
To solve this problem, we can first sort the cuboids based on their dimensions in non-decreasing order. After sorting, we can apply a dynamic programming approach to find the maximum height of stacked cuboids. The key idea is to consider each cuboid as the top cuboid and iterate over all the cuboids below it to check if the current cuboid can be placed on top of the previous cuboid. If it can be placed, we update the height of the current cuboid by adding the height of the previous cuboid.
We will maintain an array dp[] where dp[i] represents the maximum height achievable by considering the ith cuboid as the top cuboid. We initialize dp[] with the heights of the cuboids and then iterate over all cuboids to update the maximum height based on the constraints mentioned in the problem.
At the end, the maximum height of the stacked cuboids will be the maximum value in the dp[] array.
Time Complexity
The time complexity of this approach is O(n^2) where n is the number of cuboids.
Space Complexity
The space complexity is O(n) for storing the dp[] array.
Solution Code
class Solution {
public int maxHeight(int[][] cuboids) {
Arrays.sort(cuboids, (a, b) -> {
if (a[0] != b[0]) return a[0] - b[0];
if (a[1] != b[1]) return a[1] - b[1];
return a[2] - b[2];
});
int n = cuboids.length;
int[] dp = new int[n];
for (int i = 0; i < n; i++) {
dp[i] = cuboids[i][2];
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (cuboids[i][0] >= cuboids[j][0] && cuboids[i][1] >= cuboids[j][1] && cuboids[i][2] >= cuboids[j][2]) {
dp[i] = Math.max(dp[i], dp[j] + cuboids[i][2]);
}
}
}
int maxHeight = 0;
for (int height : dp) {
maxHeight = Math.max(maxHeight, height);
}
return maxHeight;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1691 (Maximum Height by Stacking Cuboids )?
This page provides optimized solutions for LeetCode problem 1691 (Maximum Height by Stacking Cuboids ) 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 1691 (Maximum Height by Stacking Cuboids )?
The time complexity for LeetCode 1691 (Maximum Height by Stacking Cuboids ) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1691 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1691 in Java, C++, or Python.