LeetCode(53)-Maximum Subarray

版权声明:XiangYida https://blog.csdn.net/qq_36781505/article/details/83514800

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.

嗯,这个题有点典型,很多地方都遇到过,题目的大致意思就是求一串数中的和的最大的子串
思路如下
从左边第一个大于0的书开始相加,判断每次相加的结果是否为最大值,然后若加起来的结果小与0的话,就说明没有往后面加的必要(也就是说,后面的不需要再加前面的了)然后就从结果小与0的后面那个正数开始相加与最大值比较就行。
代码如下

public int maxSubArray(int[] nums) {
        int max=Integer.MIN_VALUE;
        int sum=0;
        for (int i = 0; i <nums.length; i++) {
            sum+=nums[i];
            max=Math.max(max,sum);
            if(sum<=0)sum=0;
        }
        return max;
    }

猜你喜欢

转载自blog.csdn.net/qq_36781505/article/details/83514800