Maximum Subarray

Find the contiguous subarray with the largest sum.

Pattern

Kadane's Algorithm

This problem follows the Kadane's Algorithm pattern, commonly found in the Greedy category. Recognizing this pattern is key to solving it efficiently in an interview setting.

Approach

How to Solve It

Track current sum. If it goes negative, reset to 0. Update max at each step.

Key Insight

If the running sum goes negative, any future subarray is better off starting fresh — that's why you reset to the current element.

Step-by-step

  1. 1Initialize maxSum to the first element, currentSum to 0
  2. 2For each element, add it to currentSum
  3. 3If currentSum > maxSum, update maxSum
  4. 4If currentSum drops below 0, reset it to 0

Pseudocode

maxSum = nums[0]
currentSum = 0
for num in nums:
    currentSum = max(num, currentSum + num)
    maxSum = max(maxSum, currentSum)
return maxSum
Complexity Analysis

Time Complexity

O(n)

Space Complexity

O(1)
More Greedy Problems

Master this pattern with YeetCode

Practice Maximum Subarray and similar Greedy problems with flashcards. Build pattern recognition through active recall.

Practice this problem