算法53. Maximum Subarray

53. Maximum Subarray
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example:

Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Follow up:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

class Solution {
    public int maxSubArray(int[] nums) {
 
    }
}

一个整型数组,找到一个和为最大的连续子数组(至少包含一个数)并返回其和。

提高:
如果你已经钟找到 O(n) 时间复杂度的解决方法,可以尝试使用分治来解决。

解:

思路一:先找到 O(n) 时间复杂度的方法。要为O(n),则只能遍历一次;其次呢,只需要返回和,不需要返回具体哪几个数,那就计算和。判断加上当前数,值是否比之前的大,因为条件要连续,如果当前的值比加起来还大,说明前面的和为负数,直接返回当前值。当前最大值再与最大的比较,返回最大的即可。代码如下:

class Solution {
    public int maxSubArray(int[] nums) {
        int currMax = nums[0], max = nums[0];
        for (int i = 1; i < nums.length; i++) {
            currMax = Math.max(currMax + nums[i], nums[i]);
            max = Math.max(max, currMax);
        }
        return max;
    }
}

后面再去思考分治的方法。

你可能感兴趣的:(算法53. Maximum Subarray)