Skip to main content

Medium dynamic programming · arrays

The best stretch

A month of daily profit and loss. Find the stretch of days you most wish you had been open.

Write maxSubarray(nums): return the largest sum of any non-empty run of consecutive numbers. If nums is empty, return 0.

Keep ends, where ends[i] is the best sum of a run that ends exactly at day i. Call show(ends) each time you add to it and the stage draws those running totals as bars.

Example: maxSubarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]) returns 6, from the run [4, -1, 2, 1].

Tests you can see

  • maxSubarray([-2,1,-3,4,-1,2,1,-5,4])6
  • maxSubarray([5,4,-1,7,8])23

More tests are hidden. The server runs them all before a time counts.

Call show() while your code works and the run plays back here.

javascriptmaxSubarray()

Tab indents · Cmd/Ctrl+Enter runs