The strongest signal
- O(n) · Medium
- Full plan
- Python
- JavaScript
- lists
- loops
- indexes
Problem
The Albatross probe is past Jupiter now, and its signal reaches the base weaker every day. Each minute the dish measures how strong it came in; when the noise wins, the reading is negative. The dish can only record k minutes in a row, so someone has to pick the best stretch.
Write a function that takes the list of readings (whole numbers, which can be negative) and k (a whole number, 1 or more), and returns the largest sum of k readings in a row. With [3, -1, 4, 1, -5] and k = 2, the windows add up to 2, 3, 5 and -4: you return 5. You don't need to add up the whole window at every step: when it moves one place, one reading comes in and one goes out.
If every reading is negative, the best sum is negative too. If the list has fewer than k readings, there is no window: return 0.
Examples
The example
[3, -1, 4, 1, -5], 2 → 5
A window of three
[2, 1, 5, 1, 3, 2], 3 → 9
The best one is the first
[9, 8, 1, 1, 1], 2 → 17
One minute at a time
[5, -2, 7], 1 → 7
The window is the whole list
[4, -1, 2, 3], 4 → 8
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def best_window(readings, k):
passJavaScript
function bestWindow(readings, k) {
}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.