Maximum Height by Stacking Cuboids LeetCode solution in Java

1
class Solution {
2
public int maxHeight(int[][] cuboids) {
3
// Sorting all Dimensions
4
for (int[] arr : cuboids) Arrays.sort(arr);
5

6
// sort all cuboids on basis of height, if same then breadth,
7
// if same then length
8
Arrays.sort(
9
cuboids,
10
(a, b) ->
11
(b[2] - a[2] == 0 ? (b[1] - a[1] == 0 ? b[0] - a[0] : b[1] - a[1]) : b[2] - a[2]));
12

13
// use logic of LIS(Longest Increasing Subsequence)
14
return helperTab(cuboids);
15
}
16

17
public int helperTab(int[][] nums) {
18
int n = nums.length;
19
int[] currRow = new int[n + 1];
20
int[] nextRow = new int[n + 1];
21

22
for (int curr = n - 1; curr >= 0; curr--) {
23
for (int prev = curr - 1; prev >= -1; prev--) {
24
int take = 0;
25
if (prev == -1 || check(nums[curr], nums[prev])) take = nums[curr][2] + nextRow[curr + 1];
26
int notTake = 0 + nextRow[prev + 1];
27
currRow[prev + 1] = Math.max(take, notTake);
28
}
29
nextRow = currRow;
30
}
31
return nextRow[0];
32
}
33

34
// These function checks whether current cuboid can be placed above
35
// the below one or not, on the basis on condition given in question.
36
public boolean check(int[] a, int[] b) {
37
if (a[0] <= b[0] && a[1] <= b[1] && a[2] <= b[2]) return true;
38
else return false;
39
}
40
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0