Prefix Sums Answer Range Queries

Precompute a prefix slice so any sub-range sum becomes two index lookups, turning repeated O(n) scans into constant-time queries.

GoData Integrity

Code

gosnippet
20 lines
package main

import "fmt"

func main() {
	sales := []int{8, 3, 0, 5, 12, 7, 2}

	// prefix[i] = 前 i 个元素之和;prefix[0]=0 表示空区间
	prefix := make([]int, len(sales)+1)
	for i, v := range sales {
		prefix[i+1] = prefix[i] + v
	}

	// 区间 [l, r) 的和 = prefix[r]-prefix[l]:任意查询两次下标访问
	rangeSum := func(l, r int) int { return prefix[r] - prefix[l] }

	fmt.Println("total:", rangeSum(0, len(sales)))
	fmt.Println("days 2-4:", rangeSum(2, 5))
	fmt.Println("first three:", rangeSum(0, 3))
}

How execution unfolds

Prefix Sums Answer Range Queries reduces to the function main.

One loop does the cycling here: for i, v := range sales.

Caveats

  • Fully self-contained: imports, if any, come from the runtime itself.

Using it

Signature: func main()

The run emits 3 labeled sections — total:, days 2-4:, first three: — one per step.

Key statements

rangeSum := func(l, r int) int { return prefix[r] - prefix[l] }
for i, v := range sales {
	prefix[i+1] = prefix[i] + v
}
prefix := make([]int, len(sales)+1)

Interactive Tools for This Topic

FAQ

What does Prefix Sums Answer Range Queries print when run?
Invoke the file as-is — the `total:`, `days 2-4:`, `first three:` prefixes identify which step printed each line.