10
10
"""
11
11
12
12
13
- class SubArray :
14
- def __init__ (self , arr ):
15
- # we need a list not a string, so do something to change the type
16
- self .array = arr .split ("," )
17
-
18
- def solve_sub_array (self ):
19
- rear = [int (self .array [0 ])] * len (self .array )
20
- sum_value = [int (self .array [0 ])] * len (self .array )
21
- for i in range (1 , len (self .array )):
22
- sum_value [i ] = max (
23
- int (self .array [i ]) + sum_value [i - 1 ], int (self .array [i ])
24
- )
25
- rear [i ] = max (sum_value [i ], rear [i - 1 ])
26
- return rear [len (self .array ) - 1 ]
13
+ def longest_sub_array (arr :list ):
14
+ """
15
+ Find the longest continuous subarray with the maximum sum within a given list of integers.
16
+
17
+ Args:
18
+ arr (list): A list of integers.
19
+
20
+ Returns:
21
+ A Integer which is the max subarray sum in the whole array.
22
+
23
+ Examples:
24
+ >>> longest_sub_array([1, 2, 3, 2, 5])
25
+ 13
26
+
27
+ >>> longest_sub_array([5, -4, 3, -2, 1])
28
+ 5
29
+
30
+ >>> longest_sub_array([1, 2, 3, -2, 5])
31
+ 9
32
+
33
+ >>> longest_sub_array([10, 20, -30, 40, 50])
34
+ 90
35
+
36
+ >>> longest_sub_array([])
37
+ 0
38
+ """
39
+
40
+ max_so_far = arr [0 ]
41
+ max_ending_here = arr [0 ]
42
+ max_len = 1
43
+ curr_len = 1
44
+
45
+ for i in range (1 , len (arr )):
46
+ if max_ending_here < 0 :
47
+ max_ending_here = arr [i ]
48
+ curr_len = 1
49
+ else :
50
+ max_ending_here += arr [i ]
51
+ curr_len += 1
52
+ if max_ending_here > max_so_far :
53
+ max_so_far = max_ending_here
54
+ max_len = curr_len
55
+ elif max_ending_here == max_so_far :
56
+ max_len = max (max_len , curr_len )
57
+
58
+ return max_len
59
+
27
60
28
61
29
62
if __name__ == "__main__" :
30
- whole_array = input ("please input some numbers:" )
31
- array = SubArray (whole_array )
32
- re = array .solve_sub_array ()
33
- print (("the results is:" , re ))
63
+ import doctest
64
+
65
+ doctest .testmod ()
0 commit comments