Example 1
- Input
- nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
- Output
- 6
The block [4, -1, 2, 1] sums to 6, the largest of any contiguous block.
Given an integer array, find the largest possible sum of any contiguous block inside it. The block must contain at least one element and may be the whole array.
Given an integer array nums, find the contiguous subarray with the largest sum and return that sum. A subarray must keep the original order and stay unbroken.
For nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] the answer is 6 from the block [4, -1, 2, 1]. A single element also counts, so nums = [1] returns 1.
The block [4, -1, 2, 1] sums to 6, the largest of any contiguous block.
The only block is [1] itself.
The whole array sums to 23, which beats every shorter block.
A nonempty block is required. The single value -1 beats every longer block; choosing an empty block with sum zero is illegal.
A contiguous block cannot skip a negative value in its middle, but it can discard a harmful prefix. In Example 1, the sum before 4 is negative, so starting fresh at 4 beats extending it. The later -1 stays inside [4, -1, 2, 1] because the running sum remains positive and can help the next value. Track both the best block ending at the current index and the best block seen anywhere; these are different quantities.
Reveal All Subarrays Scan: intuition, complexity, and code
[-3, -1, -2], where the answer is the largest single element -1.[1], where the only block is the answer.best to zero admits an empty block and fails on [-3, -1, -2]. Seed it with an actual element.cur reports only the best block ending at the last index. Example 1 ends at 5 but the answer is 6.-1 in Example 1.When segments must stay contiguous, restart the running total the moment it turns negative and remember the best ending anywhere.