Introduction
The Maximum Subarray Sum problem is one of the most popular and frequently asked questions in Data Structures and Algorithms (DSA) interviews. This problem mainly checks how well you understand arrays and how efficiently you can optimize a solution.
In simple terms, the problem asks you to find a continuous part of the array whose elements add up to the largest possible sum.
This article explains everything in easy language, making it ideal for students, beginners, and job seekers.
What is the Maximum Subarray Sum Problem?
You are given an array of integers that can contain positive numbers, negative numbers, or both. Your task is to find a contiguous subarray (elements must be next to each other) that gives the maximum sum.
Example
Input: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Output: 6
Explanation
In the above array, the subarray [4, -1, 2, 1] produces the highest sum:
4 + (-1) + 2 + 1 = 6
Why Brute Force is Not a Good Approach
In the brute-force method, we calculate the sum of all possible subarrays and then find the maximum.
Problems with Brute Force
Too many subarrays to check
Takes a lot of time for large arrays
Time Complexity becomes O(n²)
Because of this inefficiency, brute force is not suitable for interviews or real-world applications.
What is Kadane’s Algorithm?
Kadane’s Algorithm is an optimized solution that solves the Maximum Subarray Sum problem in linear time.
The core idea is very simple:
If the current sum becomes negative, it is better to start fresh from the next element
Always keep track of the maximum sum found so far
This approach avoids unnecessary calculations.
How Kadane’s Algorithm Works (Step-by-Step)
We use two variables:
currentSum – stores the sum of the current subarray
maxSum – stores the maximum sum found till now
Steps Explained
Start by assigning the first element of the array to both
currentSumandmaxSumMove through the array one element at a time
At each element:
Decide whether to add it to the existing subarray or start a new one
Update
maxSumifcurrentSumbecomes larger
Dry Run Example (Very Important)
Array: [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Join the conversation! Your thoughts help the community grow.