-
Notifications
You must be signed in to change notification settings - Fork 0
/
maxsubarray.py
executable file
·65 lines (49 loc) · 1.65 KB
/
maxsubarray.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
61
62
63
64
65
'''
Created on Jun 22, 2013
@author: neverendingqs
'''
def kadane(inputarray):
max_ending_here = max_so_far = 0
for element in inputarray:
max_ending_here = max(0, max_ending_here + element)
max_so_far = max(max_so_far, max_ending_here)
return max_so_far
def kadane_with_subarray(inputarray):
max_ending_here = 0
meh_start_index = 0
meh_subarray_length = 0
max_so_far = 0
msf_start_index = 0
msf_subarray_length = 0
for i, element in enumerate(inputarray):
# max_ending_here = max(0, max_ending_here + element)
if (max_ending_here + element) < 0:
max_ending_here = 0
else:
if max_ending_here == 0:
meh_start_index = i
meh_subarray_length = 1
else:
meh_subarray_length += 1
max_ending_here = max_ending_here + element
# max_so_far = max(max_so_far, max_ending_here)
if max_so_far < max_ending_here:
max_so_far = max_ending_here
msf_start_index = meh_start_index
msf_subarray_length = meh_subarray_length
return msf_start_index, msf_subarray_length, max_so_far
def brute_force(inputarray):
inputarraylength = len(inputarray)
currmax = 0
currmax_index = 0
currmax_length = 0
currsum = 0
for i in range(inputarraylength):
for j in range(i, inputarraylength):
currsum += inputarray[j]
if currsum > currmax:
currmax = currsum
currmax_index = i
currmax_length = j - i + 1
currsum = 0
return currmax_index, currmax_length, currmax