Kadane’s Algorithm

Maximum subarray problem

Purushottam Banerjee
ALgo 101
3 min readJan 10, 2022

--

Problem:
In a given set of Numbers in a One-Dimensional array, Our Task is to find the largest Sum of a Subarray.

For example, for the array of values [−2, 1, −3, 4, 2, 1, −5, 4], the contiguous subarray with the largest sum is [4, 2, 1], with — 7.

Before Jumping to Solution Let us see How we can approach the given problem.

Photo by Mohammad Rahmani on Unsplash

Brute Force:

The brute approach to solve this problem is to run two for loops and for every subarray check if it is the maximum sum possible or not.

  • Run the first loop from 0 to n — 1, where n is the size of the array. — Counter i
  • Next, we will run a nested loop from i to n — 1 and add the value of the element in the nested loop to a variable currentMax.
  • Lastly, for every subarray, we will check if the currentMax is the maximum sum of all contiguous subarrays.

The problem with this approach is that it will take
Time complexity: O(N²), Where N is the size of the array.
Space complexity: O(1)

Efficient Approach :

Kadane’s original algorithm solves the problem version when empty subarrays are admitted. It scans the given array from left to right. In the jth step, it computes the subarray with the largest sum ending at each element, this sum is maintained in the variable current_sum. Moreover, it computes the subarray with the largest sum anywhere in the array by maintaining in a variable, and easily obtained as the maximum of all values current_sum seen so far.

The idea is basically memoizing the value of current_sum for each element and checking the largest among them.

Pseudo Code:

CODE :

If you have any suggestions please feel free to connect with us or comment with your thoughts.

Happy Coding.

--

--

Purushottam Banerjee
ALgo 101

Software Engineer| Film enthusiast| Story Teller || Wants to make the world better.