How long to clear the order book
Each order has to be made in one piece on a single day, and the plant has a fixed capacity per day. Orders are taken in the order they were received.
- Fill each day with orders in sequence while they still fit; the first that does not fit starts the next day.
- An order bigger than a whole day of capacity can never be made — return -1.
- A capacity of zero or less is also -1.
- An empty book takes no days.
daysToClear(orders: list<int>, dailyCapacity: int) → int
Go needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
func daysToClear(orders []int, dailyCapacity int) int {
}
Worked examples
| Call | Result |
|---|---|
daysToClear([]int{3, 4, 5}, 7) | 2 |
daysToClear([]int{7, 7}, 7) | 2 |
daysToClear([]int{8}, 7) | -1 |
daysToClear([]int{1, 1, 1}, 10) | 1 |
Hint
Track how much of today is left. When the next order does not fit, start a new day rather than splitting it.
Reference solution in Go
func daysToClear(orders []int, dailyCapacity int) int {
if dailyCapacity <= 0 {
return -1
}
days, left := 0, 0
for _, o := range orders {
if o > dailyCapacity {
return -1
}
if o > left {
days++
left = dailyCapacity
}
left -= o
}
return days
}