#1691

Maximum Height by Stacking Cuboids

Hard
ArrayDynamic ProgrammingSortingDynamic ProgrammingSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n)
💡

Intuition

Time O(n²)Space O(n)

The optimal solution involves sorting the cuboids and using dynamic programming to build the maximum height incrementally. By sorting, we ensure that we only need to check each cuboid against the previous ones, significantly reducing the complexity.

⚙️

Algorithm

4 steps
  1. 1Step 1: Sort the cuboids by width, length, and height in descending order.
  2. 2Step 2: Initialize a DP array where dp[i] represents the maximum height achievable with the i-th cuboid at the base.
  3. 3Step 3: For each cuboid, check all previous cuboids to see if they can be stacked on top, updating the DP array accordingly.
  4. 4Step 4: The result will be the maximum value in the DP array.
solution.py12 lines
1def maxHeight(cuboids):
2    # Sort cuboids by width, length, height
3    cuboids = [sorted(c) for c in cuboids]
4    cuboids.sort(reverse=True)
5    n = len(cuboids)
6    dp = [0] * n
7    for i in range(n):
8        dp[i] = cuboids[i][2]  # Base height is the height of the cuboid itself
9        for j in range(i):
10            if (cuboids[i][0] <= cuboids[j][0] and cuboids[i][1] <= cuboids[j][1]):
11                dp[i] = max(dp[i], dp[j] + cuboids[i][2])
12    return max(dp)

Complexity note: The time complexity is O(n²) due to the nested loop for checking stackable cuboids, while the space complexity is O(n) for the DP array.

  • 1Sorting cuboids helps in reducing the complexity of checking stackability.
  • 2Dynamic programming allows us to build solutions incrementally, leveraging previously computed results.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.