Power for liftoff
- O(n²) · Very hard
- Full plan
- Python
- JavaScript
- lists
- loops
Problem
The moon base runs on its solar panels: each day they collect some energy, and the lander needs goal units to lift off. The crew wants to know the fewest days in a row that are enough to collect it.
Write a function that takes energy, the list of what was collected each day (integers greater than 0; it may be empty), and goal, an integer greater than 0. Return an integer: the smallest number of consecutive days whose energy adds up to goal or more. The stretch can start on any day, and a single day counts if it is enough. If even all the days together fall short of the goal, or the list is empty, return 0.
With [2, 3, 1, 2, 4, 3] and goal 7, no single day reaches 7, but the last two add up to 4 + 3 = 7: the answer is 2.
Examples
The example
[2, 3, 1, 2, 4, 3], 7 → 2
Three days at the end
[1, 2, 3, 4, 5], 11 → 3
One day is enough
[3, 9, 2], 8 → 1
Not enough
[1, 2, 1], 10 → 0
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def shortest_run(energy, goal):
passJavaScript
function shortestRun(energy, goal) {
}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.