53. Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.

一刷
题解:
初始设置结果为Integer.MIN_VALUE,然后当前curMax小于0时重置其为0。

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {
    public int maxSubArray(int[] nums) {
        if(nums == null) return 0;
        int max=Integer.MIN_VALUE, start =0, curSum = 0;
        for(int i=0; i<nums.length; i++){
            curSum +=nums[i];
             max = Math.max(max, curSum);
           if(curSum<0) curSum = 0;
        }
        
        return max;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容