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.
Code
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
Big-O Complexity VisualizerVisualize and compare algorithm time complexities like O(1), O(log n), O(n), O(n log n), and O(n²). Plot growth curves to understand performance scaling at a glance.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.