53. 最大子序和

题目描述:

  给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。

  示例:

  输入: [-2,1,-3,4,-1,2,1,-5,4],
    输出: 6
  解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。

题解:

public class L53 {
    public static int maxSubArray(int[] nums) {
        return getMaxSub3(nums,0,nums.length-1);
    }
    //使用动态规划方法
    public static int getMaxSub(int[] nums){
        int res = Integer.MIN_VALUE;
        //建立一个数组
        int maxSub0 = 0;
        for(int index = 0;index<nums.length;index++){
            if(index == 0 || (maxSub0 < 0)){
                maxSub0 = nums[index];
            }else{
                maxSub0 = maxSub0 +nums[index];
            }
            res = maxSub0 > res?maxSub0:res;
        }
        return res;
    }
    //使用贪心法--即遇到sum <0,时候将其值置0
    public static int getMaxSub2(int[] nums){
        int res = Integer.MIN_VALUE;
        //建立一个数组
        int maxSub0 = 0;
        for(int index = 0;index<nums.length;index++){
            maxSub0 = maxSub0 +nums[index];
            res = maxSub0 > res?maxSub0:res;
            if(maxSub0 <0){
                maxSub0 = 0;
            }
        }
        return res;
    }
    //经典的分治法--待补充
    public static int getMaxSub3(int[] nums,int start,int end){
        if(end == start+1){
            return Math.max(nums[start],Math.max(nums[start] + nums[end],nums[end]));
        }else if(end == start){
            return nums[start];
        }
        int middle = (start + end)/2;
        int left = getMaxSub3(nums,start,middle);
        int right = getMaxSub3(nums,middle+1,end);
        int i = middle;int sumLeft = 0;int maxLeft = Integer.MIN_VALUE;
        int j = middle+1;int sumRight = 0;int maxRight = Integer.MIN_VALUE;
        while(i >= start){
            sumLeft += nums[i];
            maxLeft = Math.max(sumLeft,maxLeft);
            i--;
        }
        while(j <= end){
            sumRight += nums[j];
            maxRight = Math.max(maxRight,sumRight);
            j++;
        }
        return Math.max(maxLeft+maxRight,Math.max(left,right));
    }
    public static void main(String[] args) {
        int nums[] = {-2,-1,-3};
        System.out.println(maxSubArray(nums));
    }
}
原文地址:https://www.cnblogs.com/mayang2465/p/11982280.html