|
| 1 | +package com.hellokoding.algorithm; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import java.util.Comparator; |
| 5 | + |
| 6 | +public class DP_BoxStacking { |
| 7 | + static class Box { |
| 8 | + int height; |
| 9 | + int width; |
| 10 | + int depth; |
| 11 | + int area; |
| 12 | + |
| 13 | + Box(int height, int width, int depth) { |
| 14 | + this.height = height; |
| 15 | + this.width = width; |
| 16 | + this.depth = depth; |
| 17 | + this.area = this.width * this.depth; |
| 18 | + } |
| 19 | + } |
| 20 | + |
| 21 | + static int findMaxHeight(Box[] arr, int N) { |
| 22 | + Box[] boxes = new Box[N*3]; |
| 23 | + |
| 24 | + for (int i = 0; i < N; i++) { |
| 25 | + Box current = arr[i]; |
| 26 | + boxes[i*3] = new Box(current.height, Math.max(current.width, current.depth), Math.min(current.width, current.depth)); |
| 27 | + boxes[i*3 + 1] = new Box(current.width, Math.max(current.height, current.depth), Math.min(current.height, current.depth)); |
| 28 | + boxes[i*3 + 2] = new Box(current.depth, Math.max(current.height, current.width), Math.min(current.height, current.width)); |
| 29 | + } |
| 30 | + |
| 31 | + Arrays.sort(boxes, Comparator.comparing(x -> x.area, Comparator.reverseOrder())); |
| 32 | + N *= 3; |
| 33 | + |
| 34 | + int[] maxHeights = new int[N]; |
| 35 | + for (int i = 0; i < N; i++) { |
| 36 | + maxHeights[i] = boxes[i].height; |
| 37 | + } |
| 38 | + |
| 39 | + for (int i = 0; i < N; i++) { |
| 40 | + int maxHeightBeforeI = 0; |
| 41 | + for (int j = 0; j < i; j++) { |
| 42 | + if (boxes[j].width > boxes[i].width && boxes[j].depth > boxes[i].depth) |
| 43 | + maxHeightBeforeI = Math.max(maxHeightBeforeI, maxHeights[j]); |
| 44 | + } |
| 45 | + maxHeights[i] = maxHeightBeforeI + boxes[i].height; |
| 46 | + } |
| 47 | + |
| 48 | + return Arrays.stream(maxHeights).max().getAsInt(); |
| 49 | + } |
| 50 | + |
| 51 | + public static void main(String[] args) { |
| 52 | + Box[] arr = new Box[4]; |
| 53 | + arr[0] = new Box(4, 6, 7); |
| 54 | + arr[1] = new Box(1, 2, 3); |
| 55 | + arr[2] = new Box(4, 5, 6); |
| 56 | + arr[3] = new Box(10, 12, 32); |
| 57 | + |
| 58 | + System.out.println(findMaxHeight(arr, 4)); |
| 59 | + } |
| 60 | +} |
0 commit comments