Skip to content

Commit 9f3458d

Browse files
authored
Create main.cpp
1 parent 0a09f99 commit 9f3458d

File tree

1 file changed

+42
-0
lines changed
  • 24 - Dynamic Programming Problems/21 - Maximum Height by Stacking Cuboids

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
public:
3+
// Function to solve the maximum height problem using dynamic programming
4+
int solve(vector<vector<int>>& cuboids, int n) {
5+
vector<int> dp(n); // Array to store the maximum height of the tower ending at cuboid i
6+
int maxHeight = 0; // Variable to store the overall maximum height of the tower
7+
8+
// Loop through each cuboid (i represents the current cuboid being considered for the tower)
9+
for (int i = 0; i < n; i++) {
10+
dp[i] = cuboids[i][2]; // The initial height for each cuboid is its own height (third dimension)
11+
12+
// Try to stack the current cuboid on top of all previously considered cuboids (j represents the previous cuboid)
13+
for (int j = 0; j < i; j++) {
14+
// Check if cuboid j can fit under cuboid i by comparing the dimensions
15+
if (cuboids[j][0] <= cuboids[i][0] && // width of cuboid j <= width of cuboid i
16+
cuboids[j][1] <= cuboids[i][1] && // length of cuboid j <= length of cuboid i
17+
cuboids[j][2] <= cuboids[i][2]) { // height of cuboid j <= height of cuboid i
18+
// If it fits, update the dp value for cuboid i to include the height of cuboid j
19+
dp[i] = max(dp[i], dp[j] + cuboids[i][2]);
20+
}
21+
}
22+
23+
// Update the overall maximum height after considering the current cuboid
24+
maxHeight = max(maxHeight, dp[i]);
25+
}
26+
27+
return maxHeight; // Return the maximum height that can be achieved
28+
}
29+
30+
// Function to find the maximum height of the tower that can be made from the given cuboids
31+
int maxHeight(vector<vector<int>>& cuboids) {
32+
// Sort the dimensions of each cuboid in non-decreasing order
33+
for (auto& cube : cuboids) {
34+
sort(cube.begin(), cube.end()); // Sorting each cuboid's dimensions (height, width, length)
35+
}
36+
37+
// Sort the cuboids by their dimensions to ensure the cuboids are arranged in the right order for the DP approach
38+
sort(cuboids.begin(), cuboids.end()); // Sorting cuboids lexicographically by their dimensions
39+
40+
return solve(cuboids, cuboids.size()); // Call the solve function to compute the maximum height
41+
}
42+
};

0 commit comments

Comments
 (0)