BM72 - Maximum sum of consecutive subarrays

topic

Input an integer array array with a length of n, one or more consecutive integers in the array form a sub-array, and the minimum length of the sub-array is 1. Find the maximum of the sum of all subarrays.

data range:

1<=n<=2×10^5

−100<=a[i]<=100

Requirements: time complexity is O(n), space complexity is O(n)

Advanced: Time complexity is O(n), space complexity is O(1)

Example 1

enter:

[1,-2,3,10,-4,7,2,-5]

return value:

18

illustrate:

According to the analysis, the subarray [3,10,-4,7,2] of the input array can obtain a maximum sum of 18

Example 2

enter:

[2]

return value:

2

Example 3

enter:

[-10]

return value:

-10


the code

import java.util.*;

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     * @param array int整型一维数组
     * @return int整型
     */
    public int FindGreatestSumOfSubArray (int[] array) {
        //1.创建dp表
        //2.初始化
        int n = array.length;
        //初始化数组最前面多加一个元素,多加的元素值为0
        int[] dp = new int[n + 1];

        //3.填表
        int ret = Integer.MIN_VALUE;
        for (int i = 1; i <= n; i++) {
            //注意实际数组array下标和dp表下标有一个偏移量
            dp[i] = Math.max(array[i - 1], dp[i - 1] + array[i - 1]);
            ret = Math.max(ret, dp[i]);
        }

        //4.返回值
        return ret;
    }
}

Guess you like

Origin blog.csdn.net/WWXDwrn/article/details/131589129