/src/main/java/org/rajivprab/sandbox/cuboid_stacking/CuboidStacking.java
Java | 46 lines | 26 code | 4 blank | 16 comment | 3 complexity | b31bad910669786bd433ded9bdc9ded3 MD5 | raw file
- package org.rajivprab.sandbox.cuboid_stacking;
- import com.google.common.collect.Lists;
- import java.util.*;
- import java.util.stream.Collectors;
- /**
- * https://leetcode.com/problems/maximum-height-by-stacking-cuboids/
- *
- * 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.
- *
- * ---------------------
- *
- * Solution used:
- * https://leetcode.com/problems/maximum-height-by-stacking-cuboids/discuss/970293/JavaC%2B%2BPython-DP-Prove-with-Explanation
- */
- class CuboidStacking {
- static int getMaxHeight(List<List<Integer>> cuboids) {
- List<Cuboid> sortedCuboids = cuboids.stream().map(Cuboid::getOrientedCuboid).collect(Collectors.toList());
- Collections.sort(sortedCuboids, Comparator.comparingInt(o -> o.height));
- return getMaxHeightSorted(sortedCuboids);
- }
- private static int getMaxHeightSorted(List<Cuboid> cuboids) {
- int[] maxHeightWhenUsedAsBase = new int[cuboids.size()];
- for (int baseIndex=0; baseIndex<cuboids.size(); baseIndex++) {
- Cuboid base = cuboids.get(baseIndex);
- maxHeightWhenUsedAsBase[baseIndex] = base.height;
- for (int secondIndex=0; secondIndex<baseIndex; secondIndex++) {
- Cuboid second = cuboids.get(secondIndex);
- if (second.canStackOnTopOf(base)) {
- int height = base.height + maxHeightWhenUsedAsBase[secondIndex];
- maxHeightWhenUsedAsBase[baseIndex] = Math.max(maxHeightWhenUsedAsBase[baseIndex], height);
- }
- }
- }
- return Arrays.stream(maxHeightWhenUsedAsBase).max().getAsInt();
- }
- }