Skip to content

1691. Maximum Height by Stacking Cuboids 👍

  • Time: $O(n^2)$
  • Space: $O(n)$
 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
class Solution {
 public:
  int maxHeight(vector<vector<int>>& cuboids) {
    // For each cuboid, sort it so that c[0] <= c[1] <= c[2].
    for (vector<int>& cuboid : cuboids)
      ranges::sort(cuboid);

    ranges::sort(cuboids);

    // dp[i] := the maximum height with cuboids[i] in the bottom
    vector<int> dp(cuboids.size());

    for (int i = 0; i < cuboids.size(); ++i)
      dp[i] = cuboids[i][2];

    for (int i = 1; i < cuboids.size(); ++i)
      for (int j = 0; j < i; ++j)
        if (cuboids[j][0] <= cuboids[i][0] &&  //
            cuboids[j][1] <= cuboids[i][1] &&  //
            cuboids[j][2] <= cuboids[i][2])
          dp[i] = max(dp[i], dp[j] + cuboids[i][2]);

    return ranges::max(dp);
  }
};
 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
class Solution {
  public int maxHeight(int[][] cuboids) {
    // For each cuboid, sort it so that c[0] <= c[1] <= c[2].
    for (int[] cuboid : cuboids)
      Arrays.sort(cuboid);

    Arrays.sort(cuboids, new Comparator<int[]>() {
      @Override
      public int compare(int[] a, int[] 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];
      }
    });

    // dp[i] := the maximum height with cuboids[i] in the bottom
    int[] dp = new int[cuboids.length];

    for (int i = 0; i < cuboids.length; ++i)
      dp[i] = cuboids[i][2];

    for (int i = 1; i < cuboids.length; ++i)
      for (int j = 0; j < i; ++j)
        if (cuboids[j][0] <= cuboids[i][0] && //
            cuboids[j][1] <= cuboids[i][1] && //
            cuboids[j][2] <= cuboids[i][2])
          dp[i] = Math.max(dp[i], dp[j] + cuboids[i][2]);

    return Arrays.stream(dp).max().getAsInt();
  }
}