We have N
boxes. Each box has 3 params: width, length, height.
I need to write a function that generates the highest possible tower using this boxes. Function must obey the following rule: all params of bottom box should be bigger than box above it.
Example
Let's say we have a box described as int array {width, length, height} -> {1, 2, 5}
, then:
input: boxes = {{2, 2, 3}, {1, 1, 1}, {3, 3, 3}, {4, 5, 4}, {7, 7, 1}}
output: 8
since {4, 5, 4} greater than {2, 2, 3} greater than {1, 1, 1}
Solution
I have found one solution that I can not understand.
void sortArrDesc(int[][] array) {
Arrays.sort(array, new java.util.Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return -1 * Integer.compare(a[2], b[2]);
}
});
}
boolean canPlaceOnTop(int prevBoxIndex, int currBoxIndex, int[][] boxes) {
if (prevBoxIndex == -1) return true;
int[] bottomBox = boxes[prevBoxIndex];
int[] topBox = boxes[currBoxIndex];
return (bottomBox[0] > topBox[0] &&
bottomBox[1] > topBox[1] &&
bottomBox[2] > topBox[2]);
}
int getHighestTower(int prevBoxIndex, int currBoxIndex, int[][] boxes) {
if (currBoxIndex == boxes.length) return 0;
int nextBoxIndex = currBoxIndex + 1;
int heightWithCurrBox = 0;
if (canPlaceOnTop(prevBoxIndex, currBoxIndex, boxes)) {
int currentBoxHeight = boxes[currBoxIndex][2];
int heightNextBox = getHighestTower(currBoxIndex, nextBoxIndex, boxes);
heightWithCurrBox = heightNextBox + currentBoxHeight;
}
int heightWithoutCurrBox =
getHighestTower(prevBoxIndex, nextBoxIndex, boxes);
return Math.max(heightWithCurrBox, heightWithoutCurrBox);
}
int getHighestTower(int[][] boxes) {
sortArrDesc(boxes);
return getHighestTower(-1, 0, boxes);
}
I don't understand what exactly getHighestTower
function do.
I mean when for example, I call function Math.sqrt(5)
I understand that I will get square root of 5. But here, in getHighestTower
function something strange happening.
It is clear that call getHighestTower(-1, 0, boxes)
will return the highest tower.
But! When we do recursive calls, I do not understand what they means.
getHighestTower(prevBoxIndex, nextBoxIndex, boxes)
What does this line means?
It seems like that call should return max possible height starting from nextBox
, but then why do we need to use prevBoxIndex
?
Moreover, this call getHighestTower(currBoxIndex, nextBoxIndex, boxes);
looks like do the same, but instead of prevBoxIndex
we use currBoxIndex
why is that?
P.S. I have already found this question, but it doesn't contain any useful information.