Python solves the maximum subsequence problem, and the subsequence can be continuous or discontinuous __python

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.