-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmax_subarray.py
More file actions
45 lines (30 loc) · 864 Bytes
/
Copy pathmax_subarray.py
File metadata and controls
45 lines (30 loc) · 864 Bytes
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
class Solution:
def maxSubArray(self, nums):
return self.calc(nums, 0, len(nums)-1)
def calc(self, nums, i, j):
if i==j:
return nums[i]
mid = (i+j)//2
l = self.calc(nums, i, mid)
r = self.calc(nums, mid+1, j)
c = self.center(nums, i, mid, j)
return max(l, r, c)
def center(self, nums, l, mid, r):
print("center", l, r, mid)
i = mid
j = mid+1
ls = float('-inf')
rs = float('-inf')
ltemp = 0
rtemp = 0
while i>=l:
ltemp += nums[i]
if ltemp>ls:
ls = ltemp
i -= 1
while j<=r:
rtemp += nums[j]
if rtemp > rs:
rs = rtemp
j += 1
return ls + rs