Kadane Scans Max Subarray With Fold
Kadane's scan folds over deltas, resetting negative running sums and tracking the best seen, handling all-negative and empty inputs.
Code
// Kadane:一次 fold 同时维护"当前延伸和"与"历史最优"
fn max_subarray(values: &[i32]) -> Option<i32> {
let (best, _) = values.iter().fold((None, 0), |(best, run), &x| {
let run = run.max(0) + x; // 前缀为负就重新起头
let best = match best {
Some(b) => b.max(run),
None => run,
};
(Some(best), run)
});
best
}
fn main() {
let deltas = [3, -7, 4, 9, -2, 8, -20, 5, 2];
println!("max subarray sum: {:?}", max_subarray(&deltas));
// 全负数组:最优就是最大的单个元素
println!("all negative: {:?}", max_subarray(&[-8, -3, -5]));
println!("empty: {:?}", max_subarray(&[]));
}How it works
The snippet is organized around the functions max_subarray and main.
A match spells out every case; omit one and the code does not compile.
What to watch for
- There is no outside surface; the standard library drives all behavior.
Using it
The one declaration to know: fn max_subarray(values: &[i32]) -> Option<i32>
The run emits 3 labeled sections — max subarray sum:, all negative:, empty: — one per step.
Running the file executes main, which drives max_subarray in order.
Key statements
let (best, _) = values.iter().fold((None, 0), |(best, run), &x| {
let run = run.max(0) + x; // 前缀为负就重新起头
let best = match best {
Some(b) => b.max(run),
None => run,
};
(Some(best), run)
});
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.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 Kadane Scans Max Subarray With Fold print when run?
- Run it as a complete program — the output lines carry labels such as `max subarray sum:`, `all negative:`, `empty:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.