DEV Community

Cover image for πŸ”₯ Kadane's Algorithm β€” The Power of Maximum Subarrays
Brajesh Lovanshi
Brajesh Lovanshi

Posted on • Edited on

πŸ”₯ Kadane's Algorithm β€” The Power of Maximum Subarrays

*Used in Amazon, Google, Microsoft Interviews πŸš€
*

Hey devs πŸ‘‹
If you’ve ever struggled with finding the maximum sum of a subarray, this is the trick you were probably missing: Kadane’s Algorithm.

It’s not just smart.
It’s ✨ interview magic ✨ β€” used by FAANG companies and loved by competitive programmers.

**πŸ“Œ What is Kadane's Algorithm?
**Kadane’s Algorithm is a dynamic programming approach used to find the maximum sum of a contiguous subarray in linear time.

_Example problem:
_
Given an array [-2,1,-3,4,-1,2,1,-5,4],
Find the subarray with the maximum sum.
Answer: [4, -1, 2, 1] with sum = 6

**βš™οΈ How does Kadane's Algorithm work?
**Kadane’s magic is this:
πŸ‘‰ At every index, decide:

Should I start a new subarray here?
Or continue the previous one?
You track two values:

currentSum: Max sum ending at the current index
maxSum: Global max across the array

int maxSum = nums[0];
int currentSum = nums[0];

for (int i = 1; i < nums.length; i++) {
    currentSum = Math.max(nums[i], currentSum + nums[i]);
    maxSum = Math.max(maxSum, currentSum);
}

Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(n)
Space Complexity: O(1)

Problem | Description
πŸ”— Maximum Subarray | Classic Kadane
πŸ”— Best Time to Buy and Sell Stock | Kadane twist
πŸ”— Maximum Sum Circular Subarray | Kadane x2
πŸ”— Maximum Product Subarray | With sign twist
πŸ”— Contiguous Array | Advanced variation

πŸ’‘ When to Use Kadane's?
When you need to find maximum/minimum sum of contiguous elements
When the array has positive and negative numbers
In profit gain, sensor data analysis, pattern detection

If you like please subscribe for such more concept and follow me on linkedIn for quick learning:

Top comments (0)