CodingMedium Arrays & Hashing

Maximum Subarray Sum (Kadane's Algorithm)

Asked for all developer roles

Why they ask this: A classic dynamic programming problem that shows whether you can improve an O(n²) idea to O(n).

Problem

Given an integer array nums with at least one element, find the contiguous subarray with the largest sum and return that sum.

Example 1

text
Input:  nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6   // subarray [4, -1, 2, 1]

Example 2

text
Input:  nums = [-3, -1, -2]
Output: -1  // the best subarray is the single element [-1]

Hints

    Approach

    Kadane's algorithm: scan once and track:

    • current: the maximum sum of a subarray that ends at index i. It is max(nums[i], current + nums[i]); if the running sum would only drag the new element down, start a new subarray.
    • best: the maximum current seen so far.

    Start both at nums[0] (not 0), so an array of only negative numbers returns its largest element instead of 0.

    Solution

    js
    function maxSubArray(nums) {
      let current = nums[0];
      let best = nums[0];
    
      for (let i = 1; i < nums.length; i++) {
        current = Math.max(nums[i], current + nums[i]);
        best = Math.max(best, current);
      }
    
      return best;
    }
    
    console.log(maxSubArray([-2, 1, -3, 4, -1, 2, 1, -5, 4])); // 6
    console.log(maxSubArray([-3, -1, -2]));                    // -1
    Time O(n) Space O(1)

    Can you explain this in your own words?

    Back to coding practice