Question: http://codility.com/demo/take-sample-test/max_double_slice_sum
Question Name: MaxDoubleSliceSum
A variant of the classic maximum subarray problem. We should travel the array twice. For the first travel, we compute and record the maximum sub-array sum, which ends at each position. At the second reverse travel, we compute and record the maximum sub-array sum, which starts at each position. Finally, we combine two sub-arrays into one double slice, and find out the maximum sum.
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
|
def
solution
(
A
)
:
A_len
=
len
(
A
)
# The length of array A
# Get the sum of maximum subarray, which ends this position
# Method: http://en.wikipedia.org/wiki/Maximum_subarray_problem
max_ending_here
=
[
0
]
*
A_len
max_ending_here_temp
=
0
for
index
in
xrange
(
1
,
A_len
-
1
)
:
max_ending_here_temp
=
max
(
0
,
A
[
index
]
+
max_ending_here_temp
)
max_ending_here
[
index
]
=
max_ending_here_temp
# Get the sum of maximum subarray, which begins this position
# The same method. But we travel from the tail to the head
max_beginning_here
=
[
0
]
*
A_len
max_beginning_here_temp
=
0
for
index
in
xrange
(
A_len
-
2
,
0
,
-
1
)
:
max_beginning_here_temp
=
max
(
0
,
A
[
index
]
+
max_beginning_here_temp
)
max_beginning_here
[
index
]
=
max_beginning_here_temp
# Connect two subarray for a double_slice. If the first subarray
# ends at position i, the second subarray starts at position i+2.
# Then we compare each double slice to get the one with the
# greatest sum.
max_double_slice
=
0
for
index
in
xrange
(
0
,
A_len
-
2
)
:
max_double_slice
=
max
(
max_double_slice
,
max_ending_here
[
index
]
+
max_beginning_here
[
index
+
2
]
)
return
max_double_slice
|