← All lints

interval_dp_by_length

L0570Idiomswarn

Interval DP stepped by length by hand

for len in ..: for l in ..: let r = l + len - 1: a table over [I.ranges]

Flagged
let n: 1..=3000 = read()
let a: [0..n]Int = read()
var dp: [n, n]Int = 0
for i in 0..n:
    dp[i, i] = a[i]
for len in 2..=n:
    for l in 0..n - len + 1:
        let r = l + len - 1
        dp[l, r] = max(a[l] - dp[l + 1, r], a[r] - dp[l, r - 1])
print(dp[0, n - 1])
Write instead
let n: 1..=3000 = read()
domain I = 0..n
let a: [I]Int = read()
var lead: [I.ranges]Int = 0
for r in I.ranges:
    let (l, last) = (r.first!, r.last!)
    lead[r] = if r.len == 1: a[l] else: max(a[l] - lead[r.drop(1)], a[last] - lead[r.drop_last(1)])
print(lead[I.range])

Why

Filling dp[l, r] for lengths 2, 3, ... with the end computed as l + len - 1 is the usual order for an interval DP, since every smaller interval is done before it is read. Written by hand it is three index variables, a loop bound (n - len + 1) that is easy to get off by one, and a square table half of which is never used. var dp: [I.ranges]T keys the table by the ranges of a domain, and for r in I.ranges visits them shortest first, so the order is the type's and not a convention. r.first! and r.last! are the ends, r.drop(1) and r.drop_last(1) the ranges one shorter, and lead[I.range] the whole. There is no automatic fix, since the base case and the recurrence move into the range form together. The rule needs a table indexed by [l, r] (or [l][r]) in the inner loop. Loops with the start outside and the length inside (prefix sums from each start) are not reported.

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
let n: 1..=3000 = read()
let a: [0..n]Int = read()
var best = 0
for l in 0..n:
    var s = 0
    for len in 1..=n - l:
        let r = l + len - 1
        s += a[r]
        best = max(best, s)
print(best)

Turn it off

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

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