You are on page 1of 1

Kadane’s Algorithm

Kadane’s algorithm is an iterative dynamic programming algorithm in


which we search for a maximum sum contiguous subarray within a
one-dimensional numeric array.
Working of Kadane’s Algorithm

Some of you may think it’ll be a sum of all elements in an array. But what if there will be negative
integer elements in the array, which will decrease the array’s total sum.

Thus, we can see that the sum of all elements in an array isn’t always the case.

A simple idea of Kadane’s algorithm is to look for all positive contiguous segments of the array and
keep track of the maximum sum contiguous subarray among all positive segments.

First, we will consider two elements, one which stores the maximum end of the subarray and
another which stores the maximum sum so far.

Let these two variables be max_ending_here and max_so_far, respectively.

We will initialise both of them to 0.

Each time we get a positive sum, we compare it with max_so_far and update max_so_far if it is
greater than it.

This logic is written in the form of an algorithm as follows:

Start

max_so_far = 0

max_ending_here = 0

Loop for each element of the array

max_ending_here = max_ending_here + a[i]

if(max_ending_here < 0)

max_ending_here = 0

if(max_so_far < max_ending_here)

max_so_far = max_ending_here

5. return max_so_far

You might also like