Maximum Subarray 解题报告

版权声明:转载请注明本文源地址 https://blog.csdn.net/qwe6112071/article/details/71699716

Maximum Subarray

Description

Given an array of integers, find a contiguous subarray which has the largest sum.

Notice

The subarray should contain at least one number.

Example

Given the array [−2,2,−3,4,−1,2,1,−5,3], the contiguous subarray [4,−1,2,1] has the largest sum = 6.

Challenge

Can you do it in time complexity O(n)?

实现思路

要求解数组的最大连续子数组,我们可以基于动态规划的思路去思考,
对于数组前k(1…数组长度)项的最大连续子数组和,只有两种情况:
1. 包含最后一项,加上最后一项为最大
2. 不包含最后一项,前面已求得
对于1、2,分别对应了一个局部最大值和全局最大值,即假设我在求索引到数组第i项的最大子数组和,局部最大值涵括子数组的第i-1项,全局最大值则不一定包括子数组的第i-1项,但它是前面数组中的最大子数组和。
在求解到数组第i项数的局部最大值和最小值,根据定义:
1. 局部最小值local[i] = Math.max(local[i-1]+nums[i],nums[i])
2. 全局最大值global[i] = Math.max(global[i-1],local[i])
通过一遍求解,global[nums.length-1]就是我们整个数组的最大连续子数组和。
在整个求解过程中,local和global的第i项只和第i-1项有关,所以我们可以简化local、global成两个数,具体实现如下所示:

public class Solution {
    /**
     * @param nums: A list of integers
     * @return: A integer indicate the sum of max subarray
     */
    public int maxSubArray(int[] nums) {
        int length = nums.length;
        if(length == 0){
            return 0;
        }
        int local = nums[0],global = nums[0];
        for(int i = 1;i < length; i ++){
            local = Math.max(local + nums[i], nums[i]);
            global = Math.max(global, local);
        }
        return global;
    }
}

猜你喜欢

转载自blog.csdn.net/qwe6112071/article/details/71699716
今日推荐