|  | 
 
| 
x
马上注册,结交更多好友,享用更多功能^_^您需要 登录 才可以下载或查看,没有账号?立即注册  复制代码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) {
        
        if(nums.length == 0) return 0;
        
        int sum = 0;
        int Max = nums[0];
        
        int len = nums.length;
        
        for(int i = 0 ; i < len ; i++){
        
            sum = sum + nums[i];
            
            Max = Math.max(Max, sum);
        
            if(sum + nums[i]< nums[i]){
                sum = 0;
            }
        }
        
        return Max;
        
    }
}
 | 
 |