11. Maximum subarray
Write maxSubarray xs, the largest sum of a nonempty contiguous run of elements of xs. For [-2, 1, -3, 4, -1, 2, 1, -5, 4] the best run is [4, -1, 2, 1], with sum 6.
For the empty list, return 0. When every element is negative, the answer is the largest single element.
Examples
- Input
maxSubarray [-2, 1, -3, 4, -1, 2, 1, -5, 4]Output6 - Input
maxSubarray [1]Output1 - Input
maxSubarray [5, 4, -1, 7, 8]Output23
Submitting also runs 7 hidden tests.
Running and submitting solutions, the hints and the editorial come with the Academy Pass. The daily problem is open to every account.
Loading editor…
Type
\to in the editor, or click:Run checks your code against the examples and your custom inputs and records nothing. Submit also runs the hidden tests, confirms the axioms your proof uses and records the result. Each uses one compiler check.
ReadyLn 1, Col 1Lean 4
Draft saved in this browser