One minute
Leetcode 1564
1564. Put Boxes Into the Warehouse I
The idea of this solution is:
- We sort
boxes
. - Then, we make an array called
minimums
, and put the minimum values ofwarehouse
from left to right into the array. If you don’t understand, look at the following images: - Then we can just look from
len(minimums) - 1
to0
and check whetherminimums[i] >= boxes[boxCounter]
we can go to the next box, other wise we continue going through the loop untilminimums[i] >= boxes[boxCounter]
. - Then we can return
boxCounter
becauseboxCounter = the number of boxes we have boxes we have fitted in
.
func maxBoxesInWarehouse(boxes []int, warehouse []int) int {
boxCounter := 0
sort.Ints(boxes)
minimums := []int{warehouse[0]}
for i := 1; i < len(warehouse); i++ {
if minimums[i - 1] > warehouse[i] {
minimums = append(minimums, warehouse[i])
} else {
minimums = append(minimums, minimums[i - 1])
}
}
for i := len(minimums) - 1; i >= 0; i-- {
if boxCounter == len(boxes) {
break
}
if minimums[i] >= boxes[boxCounter] {
boxCounter++
}
}
return boxCounter
}
Read other posts