Find the max-sum contiguous subarray and its start/end index
A store dashboard shows the net change in sales for each day: positive on good days, negative on bad ones. Marketing wants to highlight the best stretch: the run of consecutive days whose changes add up to the largest total.
Implement bestStretch(changes). It finds the non-empty contiguous run of changes with the largest sum and returns that sum together with the run’s first and last index.
bestStretch(changes) // => { sum: number, start: number, end: number } | null
start and end are both inclusive indexes, so a single day has start === end.changes is empty, return null.start. If several of those share the same start, return the shortest one (smallest end).bestStretch([3, -5, 4, -1, 2, 1, -6, 2]);
// => { sum: 6, start: 2, end: 5 } (4 - 1 + 2 + 1)
bestStretch([-8, -3, -6, -3]);
// => { sum: -3, start: 1, end: 1 } (earliest of the two -3 days)
bestStretch([5, -5, 5]);
// => { sum: 5, start: 0, end: 0 } ([5], [5, -5, 5] and the last [5] tie)
bestStretch([0, 0, 3, 0]);
// => { sum: 3, start: 0, end: 2 } (earliest start wins, then shortest)
bestStretch([]);
// => null
All values are integers, and every sum fits safely in a JavaScript number.