PageRenderTime 26ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/org/rajivprab/sandbox/cuboid_stacking/CuboidStacking.java

https://gitlab.com/whacks/sandbox
Java | 46 lines | 26 code | 4 blank | 16 comment | 3 complexity | b31bad910669786bd433ded9bdc9ded3 MD5 | raw file
  1. package org.rajivprab.sandbox.cuboid_stacking;
  2. import com.google.common.collect.Lists;
  3. import java.util.*;
  4. import java.util.stream.Collectors;
  5. /**
  6. * https://leetcode.com/problems/maximum-height-by-stacking-cuboids/
  7. *
  8. * Given n cuboids where the dimensions of the ith cuboid is cuboids[i] = [widthi, lengthi, heighti] (0-indexed).
  9. * Choose a subset of cuboids and place them on each other.
  10. *
  11. * You can place cuboid i on cuboid j if widthi <= widthj and lengthi <= lengthj and heighti <= heightj. You can
  12. * rearrange any cuboid's dimensions by rotating it to put it on another cuboid.
  13. *
  14. * Return the maximum height of the stacked cuboids.
  15. *
  16. * ---------------------
  17. *
  18. * Solution used:
  19. * https://leetcode.com/problems/maximum-height-by-stacking-cuboids/discuss/970293/JavaC%2B%2BPython-DP-Prove-with-Explanation
  20. */
  21. class CuboidStacking {
  22. static int getMaxHeight(List<List<Integer>> cuboids) {
  23. List<Cuboid> sortedCuboids = cuboids.stream().map(Cuboid::getOrientedCuboid).collect(Collectors.toList());
  24. Collections.sort(sortedCuboids, Comparator.comparingInt(o -> o.height));
  25. return getMaxHeightSorted(sortedCuboids);
  26. }
  27. private static int getMaxHeightSorted(List<Cuboid> cuboids) {
  28. int[] maxHeightWhenUsedAsBase = new int[cuboids.size()];
  29. for (int baseIndex=0; baseIndex<cuboids.size(); baseIndex++) {
  30. Cuboid base = cuboids.get(baseIndex);
  31. maxHeightWhenUsedAsBase[baseIndex] = base.height;
  32. for (int secondIndex=0; secondIndex<baseIndex; secondIndex++) {
  33. Cuboid second = cuboids.get(secondIndex);
  34. if (second.canStackOnTopOf(base)) {
  35. int height = base.height + maxHeightWhenUsedAsBase[secondIndex];
  36. maxHeightWhenUsedAsBase[baseIndex] = Math.max(maxHeightWhenUsedAsBase[baseIndex], height);
  37. }
  38. }
  39. }
  40. return Arrays.stream(maxHeightWhenUsedAsBase).max().getAsInt();
  41. }
  42. }