Rolling Window Totals With A Running Sum

Compute rolling window totals with a running sum: add the entering element and subtract the leaving one instead of rescanning every window position.

GoData Integrity

Code

gosnippet
28 lines
package main

import "fmt"

// 滑动窗口和:进一个元素、出一个元素,O(n) 而不是每窗重扫 O(n*k)
func windowTotals(samples []float64, size int) []float64 {
	if size <= 0 || size > len(samples) {
		return nil
	}
	var total float64
	for _, v := range samples[:size] {
		total += v
	}
	out := make([]float64, 0, len(samples)-size+1)
	out = append(out, total)
	for i := size; i < len(samples); i++ {
		total += samples[i] - samples[i-size] // 加新出旧
		out = append(out, total)
	}
	return out
}

func main() {
	samples := []float64{2, 4, 6, 8, 3, 1}
	fmt.Println(windowTotals(samples, 3))
	fmt.Println(windowTotals(samples, 1))
	fmt.Println(windowTotals(samples, 9))
}

The running sum that skips rescanning

windowTotals(samples, size) seeds total by summing samples[:size], then advances with one line: total += samples[i] - samples[i-size] — add the element entering the window, subtract the one leaving it. That is O(n) overall instead of rescanning every window at O(n·k). Output is preallocated to the exact window count with make([]float64, 0, len(samples)-size+1).

The three calls and their shapes

[12 18 17 12]
[2 4 6 8 3 1]
[]

For size = 3 over [2, 4, 6, 8, 3, 1] the windows sum to 12, 18, 17, 12 — each value differs from its predecessor by exactly entering-minus-leaving. size = 1 degenerates to the samples themselves. size = 9 exceeds len(samples), so the guard if size <= 0 || size > len(samples) { return nil } fires and fmt.Println renders the nil slice as [].

One addition, one subtraction

total += samples[i] - samples[i-size]

One addition and one subtraction per step replace a full window re-sum — the arithmetic identity that the new window equals the old one plus the head, minus the tail.

Interactive Tools for This Topic

FAQ

How do you run Rolling Window Totals With A Running Sum?
Direct execution is enough; the script has no external requirements.