Back

Arrays & Sliding Window (Medium) / 121. Maximum Subarray Sum (Kadane's Algorithm)

00:00
1/19

121. Maximum Subarray Sum (Kadane's Algorithm)

Medium

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example 1:

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

Example 2:

Input: nums = [1]
Output: 1
  • 1

    Understand the Goal: We want to find the maximum sum of a contiguous subarray.

  • 2

    Kadane's Algorithm:

  • 3

    Iterate through the array.

  • 4

    Maintain a current_sum. Only add the next element to current_sum if current_sum is positive. If current_sum is negative, it's better to start a new subarray from the current element.

  • 5

    Wait, the logic is: current_sum = max(num, current_sum + num). This decides whether to extend the existing subarray or start a new one.

  • 6

    Keep track of the max_sum found so far.

  • 7

    Edge Cases: Array with all negative numbers (should return the single largest element, which is the least negative one).

PYTHON PLAYGROUND
PYTHON PLAYGROUND
⏳ Loading editor…