HardNo. 1691

Maximum Height by Stacking Cuboids — LeetCode 1691 Python Solution

Pattern
Sorting
Topics
Array, Dynamic Programming, Sorting
Reading time
3 min

The problem

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.

Example

Input
cuboids = [[50,45,20],[95,37,53],[45,23,12]]
Output
190
Explanation
Cuboid 1 is placed on the bottom with the 53x37 side facing down with height 95.

Python solution

PythonSolution
class Solution:
    def maxHeight(self, cuboids: List[List[int]]) -> int:
        for c in cuboids:
            c.sort()
        cuboids.sort()
        n = len(cuboids)
        f = [0] * n
        for i in range(n):
            for j in range(i):
                if cuboids[j][1] <= cuboids[i][1] and cuboids[j][2] <= cuboids[i][2]:
                    f[i] = max(f[i], f[j])
            f[i] += cuboids[i][2]
        return max(f)

Complexity

Time
O(n2)
Space · auxiliary
O(n)

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 1691. Maximum Height by Stacking Cuboids is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1691. Maximum Height by Stacking Cuboids?

LeetCode 1691. Maximum Height by Stacking Cuboids is rated Hard on LeetCode.

What is the time complexity of LeetCode 1691. Maximum Height by Stacking Cuboids?

The Python solution on this page runs in O(n2).

What is the space complexity of LeetCode 1691. Maximum Height by Stacking Cuboids?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 1691. Maximum Height by Stacking Cuboids cover?

LeetCode 1691. Maximum Height by Stacking Cuboids is tagged Array, Dynamic Programming and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.