← All lints

sliding_sum_by_hand

L0590Idiomswarn

Window sum kept by hand

cur += a[i] - a[i - k] over k..n: Prefix(a) and p.fold(j - k..j)

Flagged
let (n, k): (1..=200000, 1..=200000) = read()
let a: [0..n]Int = read()
var cur = sum(a[i] for i in 0..min(k, n))
var best = cur
for i in k..n:
    cur += a[i] - a[i - k]
    best max= cur
print(best)
Write instead
let (n, k): (1..=200000, 1..=200000) = read()
let a: [0..n]Int = read()
let p = Prefix(a)
print((min(k, n)..=n).map(j => p.fold(j - min(k, n)..j)).max()!)

Why

Keeping cur as the sum of the last k elements with cur += a[i] - a[i - k] needs a separate first loop for the first window and an index shift to get right at both ends. let p = Prefix(a) (std.prefix) answers the sum of any window in O(1)O(1) after O(n)O(n) setup: p.fold(j - k..j) is the window that ends just before j, so the windows are j in k..=n and the best one is (k..=n).map(j => p.fold(j - k..j)).max()!. Every window sum is then a read, with no state carried between iterations. A running difference of two different sequences is not reported. There is no automatic fix, because the running sum is read inside the loop that maintains it.

The practice it serves

A hand-written pattern the language or the standard library already says in one step.

Not flagged

A near miss: close to the pattern, but not it.

Near miss
// A running difference of two different sequences is not a window sum.
let (n, k): (1..=200000, 1..=200000) = read()
let a: [0..n]Int = read()
let b: [0..n]Int = read()
var cur = 0
var best = 0
for i in k..n:
    cur += a[i] - b[i - k]
    best max= cur
print(best)

Turn it off

For one block, wrap it in with lint(sliding_sum_by_hand: allow):. For a project, add sliding_sum_by_hand = "allow" under [lints] in cp.toml.

Generated from spec/lints/sliding_sum_by_hand, the same record the linter is built from.