The problem of the maximal subsequence has met many times in the written examination, today just want to summarize briefly, the maximal subsequence mainly divides into two kinds: one kind is the subsequence can be discontinuous the maximal subsequence and (this relatively simple, the idea is accumulates the non-negative number to be possible), The other is that the subsequence must be contiguous with the largest subsequence and (this slightly more complex is a dynamic programming problem), the following is a simple summary of the two issues, specifically, see the following implementation:
#!usr/bin/env python
#encoding: Utf-8
'
__author__: Yishui Cold city
function: Max sub-sequence problem
'
def test_func ( num_list):
"" To
the sum of the largest subsequence in the array, the subsequence can be discontinuous
(or it can be written as an if judgment statement to only accumulate integers)
'
Length=len (num_list)
DP =[0]*length
dp[0]=num_list[0]
for I in range (length):
Dp[i]=max (Dp[i-1]+num_list[i], dp[i-1])
Print Dp[-1]
def test_func2 (num_list): ' To the and of the
largest subsequence in the array, the subsequence must be continuous
'
Length=len (num_list)
max_value=-10000000000
tmp=0
for I in range (length):
Tmp=max (Tmp+num_list[i], num_list[i])
Max_value=max (Max_value, tmp)
print Max_value
if __name__ = = ' __main__ ':
num_list=[-4, 3, 56,-15 , 0, -14, 4]
test_func (num_list)
print '----------------------------------------------------'
TEST_FUNC2 (Num_list)
The results are as follows;
----------------------------------------------------
[finished in 0.3s]
Of course, the maximal subsequence and the problem can also be transformed into the maximum subsequence product problem.