[Leetcode] Maximum sum of consecutive sub-arrays

Problem Description:

        Enter an integer array. There are positive and negative numbers in the array. One or more consecutive integers in the array form a sub-array. Find the maximum value of the sum of all sub-arrays.

         The required time complexity is O(n).

Example 1:

输入: nums = [-2,1,-3,4,-1,2,1,-5,4]
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

problem analysis:

       This problem can be solved using dynamic programming. The dynamic programming method can also be considered as a table filling method, and a dynamic programming table needs to be constructed. A table is constructed here, and the element value at each position in the table indicates the maximum value when the current position is the last position of the subarray. The specific approach is:

  1. Initialization: define the maximum sum of the variable maxv record sub-array, the initial value is the first element of the list lists[0];
  2. To traverse the list, if the value of the previous element is negative, then the current element value remains unchanged; if it is positive, then add the previous element value as the current element value;
  3. Compare the current element value with maxv, and maxv takes the larger value

Take the list nums = [-2,1,-3,4,-1,2,1,-5,4] as an example:

 

nums -2 1 -3 4 -1 2 1 -5 4
dp -2 1 -2 4 3 5 6 1 5
maxv -2 1 1 4 4 5 6 6 6

 

Analysis of Algorithms:

          The algorithm only needs to traverse the nums array once, so the time complexity is O(n). Using a constant amount of extra space, the space complexity is O(1).

Coding implementation:

class Solution:
    def maxSubArray(self, lists: List[int]) -> int:
        maxv = lists[0]
        for i in range(1,len(lists)):
            if lists[i-1]>0:
                lists[i] += lists[i-1]
            if lists[i] > maxv:
                maxv = lists[i]
        return maxv
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw ==uploading.4e448015.gifFailed to re-upload cancel wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw ==

 

 

Guess you like

Origin blog.csdn.net/VinWqx/article/details/104988950