11. Maximum subarray

MediumProgramAcademy Pass20 points

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

  1. InputmaxSubarray [-2, 1, -3, 4, -1, 2, 1, -5, 4]Output6
  2. InputmaxSubarray [1]Output1
  3. InputmaxSubarray [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.

Solution.lean
Loading editor…

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