/
MaximumHeightByStackingCuboids.cpp
54 lines (42 loc) · 1.47 KB
/
MaximumHeightByStackingCuboids.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
Given n cuboids where the dimensions of the ith cuboid is
cuboids[i] = [widthi, lengthi, heighti] (0-indexed).
Choose a subset of cuboids and place them on each other.
You can place cuboid i on cuboid j if widthi <= widthj and
lengthi <= lengthj and heighti <= heightj.
You can rearrange any cuboid's dimensions by rotating it
to put it on another cuboid.
Return the maximum height of the stacked cuboids.
class Solution {
public:
bool check(vector<int> base, vector<int> newBox){
if(newBox[0] <= base[0] && newBox[1] <= base[1] && newBox[2] <= base[2]){
return true;
}
else{
return false;
}
}
int solve(int n, vector<vector<int>>& a){
vector<int> currRow(n+1,0);
vector<int> nextRow(n+1,0);
for(int curr = n-1; curr >= 0; curr--){
for(int prev = curr-1; prev >= -1; prev--){
int take = 0;
if(prev == -1 || check(a[curr] , a[prev])){
take = a[curr][2] + nextRow[curr + 1];
}
int notTake = 0 + nextRow[prev + 1];
currRow[prev + 1] = max(take, notTake);
}
nextRow = currRow;
}
return nextRow[0];
}
int maxHeight(vector<vector<int>>& cuboids) {
for(auto &a : cuboids){
sort(a.begin(), a.end());
}
sort(cuboids.begin(), cuboids.end());
return solve(cuboids.size(), cuboids);
}
};