CA 10 - Kadanes Algorithm
Kadane's Algorithm
You are given an integer array arr[]. You need to find the maximum sum of a subarray (containing at least one element) in the array arr[]
Input: arr[] = [2, 3, -8, 7, -1, 2, 3]
Output: 11
Explanation: The subarray [7, -1, 2, 3] has the largest sum 11.
Input: arr[] = [-2, -4]
Output: -2
Explanation: The subarray [-2] has the largest sum -2.Input: arr[] = [5, 4, 1, 7, 8]
Output: 25
Explanation: The subarray [5, 4, 1, 7, 8] has the largest sum 25.
Time Complexity: O(n)
Auxiliary Space: O(1)
CODE:
The problem can be solved with the brute force method, of using two for loop to obtain the maximum sum array, but the time complexity will be O(n^2) but the constraint for the time complexity is O(n). Thus, we make use of the Kadane's Algorithm.
class Solution:
def maxSubarraySum(self, arr):
n = len(arr)
currmax = arr[0]
globalmax = arr[0]
for i in range(1,n):
currmax = max(arr[i],arr[i]+currmax)
globalmax = max(currmax,globalmax)
return globalmax
Comments
Post a Comment