Kadane's Algorithm

Asked atAtlassianGoogleHHashedInNinjacart
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given an integer array nums, find the subarray with the largest sum and return the sum of the elements present in that subarray.

A subarray is a contiguous non-empty sequence of elements within an array.

Input: nums = [2, 3, 5, -2, 7, -4] Output: 15 Explanation: The subarray from index 0 to index 4 has the largest sum = 15

Input: nums = [-2, -3, -7, -2, -10, -4] Output: -2 Explanation: The element on index 0 or index 3 make up the largest sum when taken as a subarray

Input: nums = [-1, 2, 3, -1, 2, -6, 5]

  • 1 <= nums.length <= 105
  • -104 <= nums[i] <= 104

cpp

class Solution {
public:
    int maxSubArray(vector<int>& nums) {
        
    }
};

java

class Solution {
    public int maxSubArray(int[] nums) {
        
    }
}

python

class Solution:
    def maxSubArray(self, nums):

javascript

class Solution {
    maxSubArray(nums) {

    }
}

csharp

public class Solution {
    /**
     * Given an integer array nums, find the subarray with the largest sum and return its sum.
     */
    public int MaxSubArray(List<int> nums) {
        
    }
}

go

func maxSubArray(nums []int) int {
	//your code goes here
}
Stuck? Show a way to structure it+
  1. 01Track the best sum of a non-empty subarray ending at the current index.
  2. 02Choose between starting at the current value and extending the previous ending sum.
  3. 03Update a global maximum from every ending position.
  4. 04Initialize from the first element so all-negative inputs remain correct.

Reference answer

Then expect these follow-ups

  • How would you return the subarray boundaries?

    Tests: state reconstruction

  • How would you find the maximum circular subarray?

    Tests: pattern extension

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question