码迷,mamicode.com
首页 > 其他好文 > 详细

53. Maximum Subarray

时间:2017-08-06 19:36:36      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:div   blog   nbsp   hat   mcs   i++   element   ref   code   

https://leetcode.com/problems/maximum-subarray/description/

 

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.

click to show more practice.

More practice:

If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

 
Sol 1:
 
public class Solution {
    public int maxSubArray(int[] nums) {
        
        // DP
        // Time O(N) Space O(1)
        
        int maxLocal = nums[0];
        int global = nums[0];
        for (int i = 1; i < nums.length; ++i){
            maxLocal = Math.max(nums[i], nums[i] + maxLocal);
            global = Math.max(global, maxLocal);
        }
        
        return global;
        
    }
}

 

 

Sol 2:

 

(Unsolved -- don‘t know what cur_min is doing here...)

 

public class Solution {
    public int maxSubArray(int[] nums) {
        
        // Time O(n) Space O(n)
        
        return mcss(nums, 0, nums.length);
        
    }
    
    // find the max sum of the continuous array 
    
    public static int mcss(int[] nums, int begin, int end){
        final int n = end - begin;
        int[] sum = new int[n + 1]; // the sum of n elements in the front
        
        int result = Integer.MIN_VALUE;
        int cur_min = sum[0];
        for (int i = 1; i <= n; i++){
            sum[i] = sum[i - 1] + nums[begin + i - 1];
        }
        for (int i = 1; i <= n; i++){
            result = Math.max(result, sum[i] - cur_min);
            cur_min = Math.min(cur_min, sum[i]);
        }
        return result;
        
        
    }
    
    
}

 

53. Maximum Subarray

标签:div   blog   nbsp   hat   mcs   i++   element   ref   code   

原文地址:http://www.cnblogs.com/prmlab/p/7295514.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!