Maximum Subarray Sum (Kadane)

medium Arrays

Problem

Read an array. Print the largest sum of a non-empty continuous part (subarray).

Constraints

  • 1 <= n <= 10^5
  • -10^4 <= a[i] <= 10^4

Examples

Input

9
-2 1 -3 4 -1 2 1 -5 4

Output

6

Solutions

Best approachTime O(n)Space O(1)

At each element we decide: continue the old subarray, or start fresh. A negative old sum is never worth keeping.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Process an array.
 * Input   : n, then n integers.
 * Output  : The best sum.
 * Approach: One pass.
 * Time    : O(n)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method solves the task. It receives the input and returns the answer.
    static long solve(int[] a) {
        // Step 1: current = best sum of a subarray that ends at this position.
        long current = a[0];
        long best = a[0];

        for (int i = 1; i < a.length; i++) {
            // Step 2: Either extend the previous subarray, or start a new one at this element.
            current = Math.max(a[i], current + a[i]);

            // Step 3: Keep the best value seen so far.
            best = Math.max(best, current);
        }
        return best;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int size = scanner.nextInt();
        int[] a = new int[size];
        for (int i = 0; i < size; i++) {
            a[i] = scanner.nextInt();
        }
        System.out.println(solve(a));
    }
}
Hints (1)
  1. When is it better to start a new subarray?