Problem 5
Maximum Subarray
Medium · 20 pts · Array, Dynamic Programming
Problem
You are given an array of N integers, which may include negative numbers. A subarray is a non-empty block of consecutive elements. Find the largest possible sum of a subarray and print it. The subarray must contain at least one element, so if every number is negative, the answer is the largest (least negative) single element. Kadane's algorithm solves this in one pass: keep the best sum of a subarray ending at the current position, and either extend it with the current element or start fresh from the current element, whichever is larger.
Input
First line: integer N. Second line: N space-separated integers.
Output
Print the maximum subarray sum.
Constraints
1 <= N <= 100000; -1000000000 <= array[i] <= 1000000000
Example input
9 -2 1 -3 4 -1 2 1 -5 4
Example output
6
Explanation
In -2 1 -3 4 -1 2 1 -5 4, the subarray 4 -1 2 1 has sum 4 - 1 + 2 + 1 = 6. Adding anything to the left or right only lowers the sum, so the answer is 6.