Sliding Window
"Which 7 days in a row had the most rain?" The direct way adds up every stretch of 7 days separately: n stretches of k days, O(n·k). But two neighbouring stretches share all but two days. A sliding window reuses that overlap.
A window of fixed size
Add up the first k values once. Then slide the window one place to the right: the new day comes in, the oldest day drops out.
rain: 4 0 12 7 1 0
└──────┘ 4 + 0 + 12 = 16
└──────┘ 16 + 7 - 4 = 19
└──────┘ 19 + 1 - 0 = 20
for i := k; i < len(xs); i++ {
sum += xs[i] - xs[i-k]
}
Each slide costs two operations, so the whole scan is O(n) whatever k is. Keep track of the best sum and where its window started.
A window that grows and shrinks
Sometimes the size isn't fixed: "the longest stretch whose total stays within the limit". Then the window has two edges that move separately. Move the right edge forward one value at a time. Whenever the sum goes over the limit, move the left edge forward until it fits again:
left, sum := 0, 0
for right, x := range xs {
sum += x
for sum > limit {
sum -= xs[left]
left++
}
// xs[left..right] is the longest fitting window that ends at right
}
It looks like a loop inside a loop, but left only ever moves forward, at most n times in total. So this is O(n) too.
This works because the values are never negative: adding a value never makes the sum smaller, and removing one never makes it bigger. With negative values, shrinking the window could push the sum up, and the trick breaks.
Task
This lesson's input is the rain in millimetres on each of 14 days.
- Complete
wettest(rain []int, k int) (start, total int): the index where thekdays in a row with the most rain start, and their total. On a tie, the earliest stretch wins.kis between 1 andlen(rain). - Complete
longestDry(rain []int, limit int) int: the most days in a row whose rain adds up to at mostlimit. No day has negative rain.