06. Kadane's Algorithm
The problem can be found at the following link: Question Link
Note: Sorry for uploading late, my exam is going on.
Problem Description
Given an integer array arr[], find the contiguous sub-array (containing at least one number) that has the maximum sum and return its sum.
Examples:
Input:
arr[] = [1, 2, 3, -2, 5]Output:
9Explanation: Max subarray sum is 9 for the elements [1, 2, 3, -2, 5].
Input:
arr[] = [-1, -2, -3, -4]Output:
-1Explanation: Max subarray sum is -1 for the element [-1].
My Approach
Kadane’s Algorithm:
We maintain two variables:
maxhfor the maximum sum ending at the current index, andmaxffor the global maximum sum across all subarrays.
Logic:
Initialize
maxhto 0 andmaxfto the smallest possible value.For each element
arr[i], updatemaxhas the maximum ofarr[i]andmaxh + arr[i]. This ensures that we either start a new subarray atarr[i]or extend the previous subarray.Update
maxfto be the maximum ofmaxfandmaxhafter processing each element.
Final Answer:
Return
maxf, which stores the maximum subarray sum.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), where
nis the length of the array. We traverse the array once, performing constant-time operations at each step.Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space for storing
maxhandmaxf.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit my LinkedIn: Any Questions. Thank you for your input; together, we strive to create a space where learning is a collaborative endeavor.
⭐ Star this repository if you find it helpful or intriguing! ⭐
📍Visitor Count
Last updated