-
-
Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathlongest_sub_array.py
60 lines (41 loc) · 1.12 KB
/
longest_sub_array.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
Author : Yvonne
This is a pure Python implementation of Dynamic Programming solution to the
longest_sub_array problem.
The problem is :
Given an array, to find the longest and continuous sub array and get the max sum of the
sub array in the given array.
"""
def longest_subarray(arr: list):
"""
Find the longest continuous subarray with the maximum sum.
Args:
arr (list): A list of integers.
Returns:
A Integer which is the max subarray sum in the whole array.
Examples:
>>> longest_subarray([1, 2, 3, 2, 5])
13
>>> longest_subarray([5, -4, 3, -2, 1])
5
>>> longest_subarray([1, 2, 3, -2, 5])
9
>>> longest_subarray([10, 20, -30, 40, 50])
90
>>> longest_subarray([])
0
"""
if not arr:
return 0
max_sum = arr[0]
current_sum = arr[0]
for i in range(1, len(arr)):
if arr[i] > (current_sum + arr[i]):
current_sum = arr[i]
else:
current_sum += arr[i]
max_sum = max(max_sum, current_sum)
return max_sum
if __name__ == "__main__":
import doctest
doctest.testmod()