Seawolf 发表于 2019-9-1 06:02:46

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: 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;
      
      int len = nums.length;
      
      for(int i = 0 ; i < len ; i++){
      
            sum = sum + nums;
            
            Max = Math.max(Max, sum);
      
            if(sum + nums< nums){
                sum = 0;
            }
      }
      
      return Max;
      
    }
}
页: [1]
查看完整版本: leetcode 53. Maximum Subarray