Skip to content

Commit f64b602

Browse files
SandersLincclauss
authored andcommitted
Update max_sub_array.py (#1000)
* Update max_sub_array.py added another method of computing maximum sum subarray * Update max_sub_array.py * Update max_sub_array.py
1 parent f195d92 commit f64b602

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

Diff for: dynamic_programming/max_sub_array.py

+22-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
author : Mayank Kumar Jha (mk9440)
33
"""
44
from __future__ import print_function
5-
5+
from typing import List
66
import time
77
import matplotlib.pyplot as plt
88
from random import randint
@@ -37,7 +37,27 @@ def find_max_cross_sum(A,low,mid,high):
3737
right_sum=summ
3838
max_right=i
3939
return max_left,max_right,(left_sum+right_sum)
40-
40+
41+
def max_sub_array(nums: List[int]) -> int:
42+
"""
43+
Finds the contiguous subarray (can be empty array)
44+
which has the largest sum and return its sum.
45+
46+
>>> max_sub_array([-2,1,-3,4,-1,2,1,-5,4])
47+
6
48+
>>> max_sub_array([])
49+
0
50+
>>> max_sub_array([-1,-2,-3])
51+
0
52+
"""
53+
best = 0
54+
current = 0
55+
for i in nums:
56+
current += i
57+
if current < 0:
58+
current = 0
59+
best = max(best, current)
60+
return best
4161

4262
if __name__=='__main__':
4363
inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000]

0 commit comments

Comments
 (0)