Maximum Sum in Contiguous ArrayLoading saved progress…

Maximum Sum in Contiguous Array

You're looking at a row of daily profit-and-loss numbers for a trading desk: some days you gained, some days you lost. You want the single best streak — a run of consecutive days whose net total is the highest possible. You can't skip a bad day in the middle and stitch two good runs together; the run has to be unbroken. Given an array of numbers (positive, negative, or zero), arrayMaximumSumContiguous(nums) returns the largest sum obtainable from any contiguous, non-empty slice of that array. This is the classic maximum subarray problem, solved optimally by Kadane's algorithm.

Signature

function arrayMaximumSumContiguous(nums: number[]): number;
// returns the largest sum of any contiguous, non-empty subarray.
// the subarray must be a single unbroken run — no skipping elements.

Examples

// A mix of gains and losses. The best run is [4, -1, 2, 1], summing to 6.
// Taking the 4 alone gives only 4; dipping through -1 to reach 2 and 1 pays off,
// but the -5 just after is too costly to cross to reach the trailing 4.
arrayMaximumSumContiguous([-2, 1, -3, 4, -1, 2, 1, -5, 4]); // 6
// Every number is negative. There's no way to reach a positive sum, and an
// empty run isn't allowed — so the answer is the single least-bad element, -1.
arrayMaximumSumContiguous([-8, -3, -6, -1, -7]); // -1

Notes

  • Contiguous — the subarray is one unbroken run of adjacent elements. [1, 3] from [1, 2, 3] is not contiguous; [1, 2] and [2, 3] are.
  • Non-empty — the chosen subarray must contain at least one element. You can never return the sum of "no elements."
  • All-negative arrays return the largest single element, not 0. Because the run must be non-empty, the best you can do is pick the one element closest to zero. For [-8, -3, -1] the answer is -1, never 0.
  • Empty input returns 0. When nums is [], there is no element to pick; this implementation defines the answer as 0. (Some variants throw instead — we pick 0 here and the tests pin it down. If your contract differs, change this one line and its test.)
  • Single element — a one-element array returns that element, positive or negative. [5] is 5; [-5] is -5.
  • Don't worry about returning the subarray itself — only its sum. Recovering the indices is covered in the solution's "Going further."
Loading editor…