Learnitweb

Maximum Subarray

1. Problem statement

Given an integer array nums, find the subarray with the largest sum, and return its sum.

Example 1:

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.

Example 2:

Input: nums = [1]
Output: 1
Explanation: The subarray [1] has the largest sum 1.

2. Core Idea of Kadane’s Algorithm

At every element in the array, we decide:

  • Should we extend the previous subarray by adding this element?
  • Or should we start a new subarray beginning at this element?
  • At each step, ask: “Would it be better to start over from here or continue?”
  • If your current sum becomes worse than starting fresh, reset it.

We keep track of two variables:

  • currentMax: Maximum subarray sum ending at current index.
  • maxSoFar: Maximum sum found so far at any point.

At each step:

currentMax = max(currentElement, currentMax + currentElement)
maxSoFar = max(maxSoFar, currentMax)

This allows you to skip over “bad” parts of the array and start from a more promising point.

3. Step-by-Step Walkthrough with Table

Let’s go through nums = [-2,1,-3,4,-1,2,1,-5,4] step by step.

Index (i)Element (nums[i])currentMaxmaxSoFarExplanation
0-2-2-2Start with first element
11max(1, -2+1) = 11Better to start fresh
2-3max(-3, 1+(-3)) = -21Add -3 lowers sum, so start fresh
34max(4, -2+4) = 44Start new from 4
4-1max(-1, 4+(-1)) = 34Continue from 4
52max(2, 3+2) = 55Continue
61max(1, 5+1) = 66Continue
7-5max(-5, 6+(-5)) = 16Continue (sum decreases)
84max(4, 1+4) = 56Continue

4. Java solution

public class MaximumSubarray {
    public int maxSubArray(int[] nums) {
        int currentMax = nums[0];
        int maxSoFar = nums[0];

        for (int i = 1; i < nums.length; i++) {
            currentMax = Math.max(nums[i], currentMax + nums[i]);
            maxSoFar = Math.max(maxSoFar, currentMax);
        }

        return maxSoFar;
    }
}