leecode: dynamic programming: 53. Maximum subsequence sum

Title
Given the nums an array of integers, and find a maximum of the successive sub-array (sub-array comprising a least one element), and has returned to its maximum.

Example

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The sum of consecutive sub-arrays [4,-1,2,1] is the largest, which is 6.

Input: nums = [0]
Output: 0

Suppose there is an array length of nnn , we mark the subscript as0 00 ton − 1 n-1n1 , the maximum subsequence sum is denoted asfmaxsub f_{maxsub}fm a d s a b, Then we get:
fmaxsub [0] f_{maxsub[0]}fm a d s and b [ 0 ]
f m a x s u b [ 0 → 1 ] f_{maxsub[0\to1]} fm a d s and b [ 0 1 ]
f m a x s u b [ 0 → 2 ] f_{maxsub[0\to 2]} fm a d s and b [ 0 2 ]
. . . ... ...
f m a x s u b [ 0 → n − 1 ] f_{maxsub[0\to n-1]} fm a d s and b [ 0 n - 1 ]
Then compare the sum of the largest subsequences of each length, and that's it.
Next is the calculation of the sum of subsequences of different lengths. We can start counting from 0, add the latter to compare, and take the maximum value. When the addition is negative, it means that the previous subsequence sum can be discarded (because negative A + positive B<positive B), then continue to count down. Finally, the largest subsequence sum can be obtained.

class Solution(object):
    def maxSubArray(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        calSum = nums[0]
        maxSum = nums[0]
        for i in range(1, len(nums)):
            if calSum > 0:
                calSum += nums[i]
                maxSum = max(calSum, maxSum)
            
            else:
                calSum = nums[i]
                maxSum = max(calSum, maxSum)
        return maxSum           

Guess you like

Origin blog.csdn.net/eight_Jessen/article/details/113573927