Dev Helpers
← Back

Find the maximum subarray sum

Find the maximum subarray sum. A self-contained example using the JavaScript runtime.

Open this example in the interactive library

Source code

const xs = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
let best = xs[0],
  current = xs[0];
for (const x of xs.slice(1)) {
  current = Math.max(x, current + x);
  best = Math.max(best, current);
}
console.log(best);

Sample output

6