2Brute2Best
🔥0
01

Maximum subarray (DP — Kadane / Subarray Sub-pattern)

The plain Kadane step: the best subarray ending at i is a[i] alone or the one ending at i − 1 extended. Variants flip it to minimum, take the absolute value, or allow one deletion (a second running state).

Signals in the problem statement
  • ›

    "largest / smallest sum contiguous subarray"

  • ›

    "maximum absolute sum"

  • ›

    "you may delete at most one element"

What makes it different

One running value (cur) and one answer (best). If the problem allows one change (delete one element), add a second state: best sum ending here with the change already used.

Questions

ordered from “learn the idea” to “recognise it without help”
  1. 1
    Maximum Subarray
    Basic Anchor·LeetCode #53
    Medium
  2. 2
    Minimum Sum Subarray
    Basic Reinforcement·GeeksforGeeks
    Easy
  3. 3
    Maximum Absolute Sum of Any Subarray
    Slight Variation·LeetCode #1749
    Medium
  4. 4Medium

Template

kadane-template.cpp
// Kadane: cur = best sum of a subarray that ends exactly here.
// Either a[i] alone (restart) or the best one ending at i - 1, extended.
long long maxSubarray(const vector<int>& a) {
    long long cur = a[0], best = a[0];             // not 0: all-negative arrays need a real answer
    for (size_t i = 1; i < a.size(); i++) {
        cur = max((long long)a[i], cur + a[i]);    // extend or restart
        best = max(best, cur);
    }
    return best;
}
Remember this · DP — Kadane / Subarray
Trigger
Maximum (or minimum) sum/product of a contiguous subarray, stock buy/sell, circular arrays.
Think
Is the best subarray ending at i either "i alone" or "best ending at i−1, plus i"?
Key question
Should I extend or restart?