Maximum Subarray — Greedy
Given a long list of daily cash changes, report the largest total any unbroken run of days can reach, even if every day lost money.
Greedy · Easy
The problem
nums[i] is a bank branch's net cash change on day i, and you want its best streak. Find the contiguous stretch of at least one day whose total is largest, and return that total.
The story
A bank branch tracks its net daily cash change for a dozen days or well over a thousand, each day between -10 and 10. The manager wants the best streak: the unbroken run of at least one day with the largest total. If every day was negative, the best streak is the single least-bad day. Report that total.
What to return
- Return the largest sum over all non-empty contiguous subarrays.
- The stretch must contain at least one element, so a list of only negatives gives its largest single element.
Constraints
- 1 <= nums.length <= 1500
- -10 <= nums[i] <= 10
- Your code may run at most 18,000 counted steps on the largest case.
Example
- Input
nums = [4, -1, 6, 3, -2, 5]- Output
15