The oasis caravan
- O(n²) · Very hard
- Full plan
- Python
- JavaScript
- division
- loops
- lists
Problem
Tariq leads a camel caravan around a circuit of Silk Road oases that ends where it begins. At each oasis he fills the waterskins with whatever is there, and each leg to the next one uses up its own share. You get water and cost, two lists of the same length (at least one) with whole numbers from 0 up: at oasis i you load water[i] liters, with no limit, and the leg to the next oasis costs cost[i]; from the last one you go back to 0. Leaving oasis s with empty waterskins, you load, walk the leg, load at the next one, and so on until back at s. If the water drops below zero after a leg, that start fails; arriving with exactly 0 is fine. Return the smallest start that makes the full loop, or -1 if none does.
With water [1, 2, 3, 4, 5] and cost [3, 4, 5, 1, 2]: from 0, 1 and 2 the water runs out on the first leg. From 3: 4-1=3, 3+5-2=6, 6+1-3=4, 4+2-4=2, 2+3-5=0. He gets home with nothing left: you return 3.
Examples
The example
[1, 2, 3, 4, 5], [3, 4, 5, 1, 2] → 3
No start makes it
[2, 3, 4], [3, 4, 3] → -1
A single oasis with no cost
[0], [0] → 0
Arriving with empty waterskins counts
[3, 1], [2, 2] → 0
Two starts work, the smallest wins
[0, 3, 3], [1, 1, 1] → 1
Surviving the first leg is not enough
[3, 0, 4], [1, 4, 2] → 2
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def starting_oasis(water, cost):
passJavaScript
function startingOasis(water, cost) {
}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.