-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMaximumSumSubarray.py
45 lines (38 loc) · 947 Bytes
/
MaximumSumSubarray.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
arr = [4,-11,1,6,2,3,-2]
#Maximum sum subarray
'''
TC - O(N2) | SC - O(1)
'''
MaxSum = -11111111
for i in range(len(arr)):
s = 0
for j in range(i,len(arr)):
s += arr[j]
if s > MaxSum:
MaxSum = s
print('MaxSum is ->',MaxSum)
'''
TC - O(N) | SC - O(1)
'''
class Solution:
# @param A : tuple of integers
# @return an integer
def maxSubArray(self, arr):
import sys
MaxSum = -sys.maxsize - 1
# for i in range(len(arr)):
# s = 0
# for j in range(i,len(arr)):
# s += arr[j]
# if s > MaxSum:
# MaxSum = s
# return MaxSum
#Kadane Algo
max_end_here = 0
for i in arr:
max_end_here += i
if MaxSum < max_end_here:
MaxSum = max_end_here
if max_end_here < 0:
max_end_here = 0
return MaxSum