1691. 堆叠长方体的最大高度
![](https://img-blog.csdnimg.cn/img_convert/e21caab3e0c4ee206dbf8c8d851cbcb6.png)
![](https://img-blog.csdnimg.cn/img_convert/43408cedd4ec81419e3df821e698c82e.png)
![](https://img-blog.csdnimg.cn/img_convert/7bdfce090361a198fcc9c2cc29a5a148.png)
【排序+ DP】这道题是354. 俄罗斯套娃信封问题的再进阶,变成三维的了。首先需要把每个进行排序,让最大的边当高度,其次对所有的按照总和从小到大排序保证一定的拓扑序,然后dp的过程中取[0, i)中符合条件的最大值。
class Solution {
public int maxHeight(int[][] cuboids) {
int n = cuboids.length, ans = 0;
for (int i = 0; i < n; i++) Arrays.sort(cuboids[i]);
Arrays.sort(cuboids, (a, b) -> a[0] + a[1] + a[2] - b[0] - b[1] - b[2]);
int[] dp = new int[n];
for (int i = 0; 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]);
}
}
dp[i] += cuboids[i][2];
ans = Math.max(dp[i], ans);
}
return ans;
}
}