Problem Solving with Go course

Sorting and SearchingSliding Window

Problem Solving with Go

Display

Theme

Sorting and Searching · Test exercise

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.

  1. Complete wettest(rain []int, k int) (start, total int): the index where the k days in a row with the most rain start, and their total. On a tie, the earliest stretch wins. k is between 1 and len(rain).
  2. Complete longestDry(rain []int, limit int) int: the most days in a row whose rain adds up to at most limit. No day has negative rain.
main.go
package main

import (
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

// wettest returns where the k days in a row with the most rain start, and their total.
// On a tie, the earliest stretch wins. k is between 1 and len(rain).
func wettest(rain []int, k int) (start, total int) {
	// TODO: add up the first k days, then slide: one day in, one day out
	return 0, 0
}

// longestDry returns the most days in a row whose rain adds up to at most limit.
// No day has less than 0 mm of rain.
func longestDry(rain []int, limit int) int {
	// TODO: grow the window on the right, shrink it on the left while it's over the limit
	return 0
}

func main() {
	data, err := io.ReadAll(os.Stdin)
	if err != nil {
		fmt.Println("could not read input:", err)
		return
	}
	var rain []int
	for _, field := range strings.Fields(string(data)) {
		mm, err := strconv.Atoi(field)
		if err != nil {
			fmt.Println("bad reading:", field)
			return
		}
		rain = append(rain, mm)
	}
	start, total := wettest(rain, 3)
	fmt.Printf("wettest 3 days: from day %d, %d mm\n", start+1, total)
	fmt.Println("longest stretch with at most 5 mm in total:", longestDry(rain, 5), "days")
}
Go runtime not loaded yet

1 line · 30 B of the 1 MB limit. Submit always uses the lesson's own input.