Kadane’s algorithm is a problem solving technique that is used to efficiently solve the Maximum Subarray Problem.
You are given an array and you need to find the subarray with the maximum sum.
A subarray is a contiguous sequence of elements within the array.
If the array contains only positive numbers, the solution is straightforward: the subarray with the maximum sum would include all elements in the array.
But the challenge arises when the array contains negative numbers, making it tricky to decide which elements to include.
For example, in the array:
the subarray with the maximum sum is [4, -1, 2, 1], with a total sum of 6.
The brute force approach to solve this problem is simple.
While it works, this approach has a time complexity of O(n²), which is too slow for large inputs.
Kadane’s Algorithm optimizes this process to run in O(n) time by dynamically deciding whether to:
If adding the current element to the subarray increases the sum, extend the subarray. Otherwise, start fresh with the current element.
This ensures the sum remains as large as possible.
Let’s walk through the four possible scenarios for each element:
Here’s how Kadane’s Algorithm looks in code:
currentSum tracks the sum of the current subarray. We initialize it to the first element because that’s the only subarray we have at the start.maxSum keeps track of the highest sum found so far.nums[i]) and the current element added to the previous subarray sum (currentSum + nums[i])currentSum to the maximum of these two.