From bf65c5093b6a2bc8c82d589da762ab765cc59ed1 Mon Sep 17 00:00:00 2001 From: Mohit Majumdar <54443683+Mohit-majumdar@users.noreply.github.com> Date: Sat, 15 Oct 2022 00:38:23 +0530 Subject: [PATCH] Create Kadan's Algorithm.py This is Kadan's Algorithm which solve maximum sum of subarray problem in O(N) time complexity --- algorithms/Python/arrays/Kadan's Algorithm.py | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 algorithms/Python/arrays/Kadan's Algorithm.py diff --git a/algorithms/Python/arrays/Kadan's Algorithm.py b/algorithms/Python/arrays/Kadan's Algorithm.py new file mode 100644 index 00000000..24320d1c --- /dev/null +++ b/algorithms/Python/arrays/Kadan's Algorithm.py @@ -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))