The trough that never runs dry
- O(n log n) · Hard
- Full plan
- Python
- JavaScript
- lists
- search
- loops
Problem
Herminia keeps her cattle on dry farmland and all the water of the ranch goes through the cistern. She is going to have a new one built and she needs the exact size: any smaller and it runs dry, any bigger and it costs her more than it should. She has it written down, day by day, how much it rained and how much the cattle drank in the driest month she remembers, and she wants to decide with that.
Two things happen each day, in this order. First the rain of the day falls and goes into the cistern; whatever does not fit spills over and is lost for good. Then the cattle arrive and drink their share. The cistern starts out full to the brim. If one day the cattle arrive and there is not enough water for everything they drink, that cistern was too small.
Write a function that takes rain and drinks, two lists of the same size (at least one day) with whole numbers of 0 or more: the liters that fell and the liters that were drunk each day, in order. The cattle drink something on at least one day. Return a whole number: the liters of the smallest cistern that holds out every day of the list.
With rain of 3, 0, 5 and 0 liters and a consumption of 2, 4, 1 and 3, the answer is 6. The cistern of 6 starts at 6; on the first day the 3 liters that fell spill over, because it was already full, and the cattle leave it at 4; on the second day it does not rain and they leave it at 0; on the third it goes up to 5 and they leave it at 4; on the last one they leave it at 1. With a cistern of 5 you do not get there: on the second day the cattle ask for 4 liters and there are only 3.
Watch out for the two easy sums. The day they drink the most is not enough, and taking all the rain of the month off everything that was drunk in the month is not either, because the water that spills over does not come back. There are months of up to 60 days and the liters of each day reach a billion, so trying one size at a time does not finish.
Examples
The example, with the rain that spills over
[3, 0, 5, 0], [2, 4, 1, 3] → 6
It does not rain on the first days
[0, 2, 1], [4, 1, 3] → 5
It rains more than enough every day
[10, 10], [1, 1] → 1
A single day
[0], [7] → 7
It spills over at the start and runs short at the end
[5, 5, 0, 0, 9], [1, 1, 4, 4, 1] → 9
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def cistern(rain, drinks):
passJavaScript
function cistern(rain, drinks) {
}It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.