πDay 10. Kadane's Algorithm π§
The problem can be found at the following link: Problem Link
π‘ Problem Description:
Given an integer array arr[], you need to find and return the maximum sum possible from all the subarrays.
π Example Walkthrough:
Input:
arr[] = [2, 3, -8, 7, -1, 2, 3]
Output:
11
Explanation:
The subarray {7, -1, 2, 3} has the largest sum, which is 11.
Input:
arr[] = [-2, -4]
Output:
-2
Explanation:
The subarray {-2} has the largest sum -2.
Constraints:
$
1 β€ arr.size() β€ 10^5$$
-10^9 β€ arr[i] β€ 10^4$
π― My Approach:
Kadane's Algorithm:
The core idea is to iterate through the array and maintain two variables:
maxh: the maximum sum of the subarray that ends at the current index.maxf: the global maximum sum encountered so far.
For each element:
Update
maxhto be either the current element alone (starting a new subarray) or the current element added to the sum of the previous subarray.Update
maxfto store the larger value between the currentmaxfandmaxh.
The result is the global maximum sum of a subarray in the array.
Steps:
Initialize
maxhto 0 andmaxfto a very small value.Traverse the array to calculate the maximum sum of the subarrays.
Return
maxfas the result, which will hold the largest sum of any subarray.
π Time and Auxiliary Space Complexity π
Expected Time Complexity: O(n), where
nis the size of the array. The algorithm performs a single linear scan of the array.Expected Auxiliary Space Complexity: O(1), as we only use a constant amount of additional space.
π Solution Code
Code (C)
Code (Cpp)
Code (Java)
Code (Python)
π― Contribution and Support:
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated