Best stretch
Inputs
values is a list of 1 to 14 whole numbers, each from -9 to 9. k is a whole number from 1 to the length of values.
Your tasks
- Add up the first
knumbers in a loop. Call the resultwindow, and also keep it asbest. - Use a second loop from position
konward. Each round, add the number entering the window and take away the number leaving it. Updatebestifwindowis larger. - Complete
bestWindowSumso it returnsbest. Return it, do not print it.
Example
With values = [2, -1, 4, 3, -5, 6] and k = 3, bestWindowSum returns 6.
Rules
- A window is
kneighbouring numbers.
Test data
TEST DATA 1: values is [2, -1, 4, 3, -5, 6], k is 3
TEST DATA 2: values is [5], k is 1
Practice focus
Two pointers and sliding windows: loops that move two positions instead of one. Two pointers and sliding windows turn many quadratic answers into linear ones.