21.03.09 LeetCode53. 最大子序和

给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

 

示例 1:

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

输入:nums = [1]
输出:1
示例 3:

输入:nums = [0]
输出:0
示例 4:

输入:nums = [-1]
输出:-1
示例 5:

输入:nums = [-100000]
输出:-100000
class Solution {
    public int maxSubArray(int[] nums) {
        if(nums.length==1)
            return nums[0];
        //使用max指针和cur指针
        int max = Integer.MIN_VALUE;//存放子数组最大和
        int cur = 0;
        //更新规则,cur累加上i位置的值,如果比max大,则更新max,如果加后变负数,则cur重置为0
        for(int i = 0;i<nums.length;i++)
        {
            cur+=nums[i];
            max = cur>max?cur:max;
            cur = cur>0?cur:0;
        }
        return max;
    }
}
posted @ 2021-03-09 09:21  γGama  阅读(40)  评论(0)    收藏  举报