LeetCode : 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.
代码
每次记录以当前数为结尾的最大子数组和,注意如果count小于0的话应该重新记数,因为负数肯定会降低和的大小。

class Solution {
    public int maxSubArray(int[] nums) {
        int max = nums[0];
        int count = 0;
        for(int num : nums){
            count += num;
            max = Math.max(max, count);
            if(count<0){
                count = 0;   
            }
        }
        return max;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_16234613/article/details/89841345