Maximum Subarray Sum Visualizer
DSA Arrays Kadane

Maximum Subarray Sum Visualizer

What is Maximum Subarray

Find the contiguous slice with the largest sum. A subarray means consecutive indices — not a subsequence. Kadane keeps a running best ending at the current index. If extending hurts, start fresh from here.

  • Transition: currentSum = max(arr[i], currentSum + arr[i])
  • Best update: maxSum = max(maxSum, currentSum)
  • Complexity: one pass — O(n) time, O(1) space. Handle all-negative arrays carefully.
  • Where it shows up: stock streaks, signal peaks, and any best contiguous segment.

The problem

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

Example: nums = [-2,1,-3,4,-1,2,1,-5,4] => 6 from subarray [4,-1,2,1].

Approach

How It Works

Start from left to right and keep two key variables in mind:
1) Current running subarray (best subarray ending at current index).
2) Best answer so far (largest sum seen anywhere).
At each number, ask:
• Should I continue extending?
• Or should I restart fresh from here?

If the previous running sum is negative/hurting the total, drop it completely and restart from the current number. Then check if this new sum is the best we've seen globally.
Why it works: Single pass through array, O(n) time, O(1) space. Greedy approach finds optimal answer without backtracking.

Visualization & Algorithm Execution

Ready

Pseudocode (Kadane's Algorithm)

1function maxSubArray(nums):
2current = nums[0]
3best = nums[0]
4for i from 1 to n-1:
5current = max(nums[i], current + nums[i])
6best = max(best, current)
7return best
Trace Log:
Ready to execute...

Array State & Visualization

Current Sum

-

Max Sum Found

-

Index (i)

-

Best Range

[-, -]

Understanding the Algorithm

Line 2-3: Initialize both current and best with the first element

Line 5: KEY DECISION — At each element, ask: "Should I extend the current subarray or restart fresh?" If nums[i] is better than current+nums[i], restart from here.

Line 6: After deciding on current, check if it's the best we've seen globally.

Result: One pass through the array, tracking best subarray ending at each position and overall best.

Implementation

Python

1def max_subarray(nums):
2current = best = nums[0]
3for x in nums[1:]:
4current = max(x, current + x)
5best = max(best, current)
6return best

JavaScript

1function maxSubArray(nums) {
2let [current, best] = [nums[0], nums[0]];
3for (let i = 1; i < nums.length; i++)
4current = Math.max(nums[i], current + nums[i]);
5best = Math.max(best, current);
6return best;
7}

C

1#include <limits.h>
2int maxSubArray(int* nums, int numsSize) {
3int current = nums[0], best = nums[0];
4for (int i = 1; i < numsSize; i++) {
5current = nums[i] > current + nums[i] ? nums[i] : current + nums[i];
6best = current > best ? current : best;
7}
8return best;
9}