Create Kadan's Algorithm.py

This is Kadan's Algorithm which solve maximum sum of subarray problem in O(N) time complexity
pull/1041/head
Mohit Majumdar 2022-10-15 00:38:23 +05:30 committed by GitHub
parent 1cc547fd8b
commit bf65c5093b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 28 additions and 0 deletions

View File

@ -0,0 +1,28 @@
#kadene algo is use for get muximum sum of subarray
# we can split this algo in 3 steps
# step1 : sum = sum + arr[i]
# step2: update max, maxi = max(sum,maxi)
# if sum less 0 update sum to 0
# step 3: if sum<0 : sum = 0
def maxSum(arr,n):
sum = 0
maxi = arr[0]
for i in range(len(arr)):
sum = sum + arr[i]
maxi = max(sum,maxi)
if sum < 0:
sum = 0
return maxi
if __name__ == "__main__":
n = int(input())
arr = [int(i) for i in input().split(" ")]
print(maxSum(arr,n))