The maximum and continuous sub-tree group - - Dynamic Programming cattle off network

Title Description

Seeking the maximum and continuous sub-vector.

{6, -3, -2,7, -15,1,2,2}, and the maximum successive sub-vectors of 8 (beginning from 0, up to the third). To an array, which returns the maximum and contiguous subsequence. (Sub-vector length is at least 1)

Ideas:

(1) do their own

1. The establishment of two pointers, start and end long se is greater than 0, represents the value of desirability, mobile e pointer, and the maximum value plus a variable record

2. If the value is less than 0, the pointer movement s and e

(2) dynamic programming (Reference) link: https://www.nowcoder.com/questionTerminal/459bd355da1549fa8a49e350bf3df484?f=discussion

dp [i] expressed as elemental array [i] at the end of the subarray and maximum continuous.

To [-2, 3,4, -1, -2,1,5, -3] Example 
it can be discovered, 
dp[0] = -2
dp[1] = -3
dp[2] = 4
dp[3] = 3
And so on, you will find 
dp[i] = max{dp[i-1]+array[i],array[i]}.

Code:

1. pointer movement

# -*- coding:utf-8 -*-
class Solution:
    def FindGreatestSumOfSubArray(self, array):
        # write code here
        result = array[0]
        fin = result
        start = 0
        end = 1
        while(start<=end and end<len(array)):
            result += array[end]
            if(result<=0):
                if(result>fin):
                    fin = result
                result = 0
                start = end+1
                end = start
                continue
            if(result>fin):
                fin = result
            end += 1
        return fin

2. Dynamic Programming

class Solution:
    def FindGreatestSumOfSubArray(self, array):
        # write code here
        dp = [i for i in array]
        for i in range(1,len(array)):
            dp[i] = max(dp[i-1]+array[i],array[i])
        return max(dp)

 

Guess you like

Origin www.cnblogs.com/ditingz/p/11759189.html