LeetCode专题:53. Maximum Subarray

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/yu0_zhang0/article/details/81917088

Maximum Subarra

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.

解答

/**
 * Created by grace on 2018/8/22.
 *给定一个数组找出最大的连续字串
 * Input: [-2,1,-3,4,-1,2,1,-5,4],
 Output: 6
 Explanation: [4,-1,2,1] has the largest sum = 6.
 */
public class MaximumSubarray {
    public static int maxSubArray(int[] nums) {

        //该题属于一维动态规划
        /** 思路:当前数和前面数字之和比较,如果大于当前数那么加上当前数,如果小于当前数,就从当前数开始计算
         *  例子:Input: [-2,1,-3,4,-1,2,1,-5,4]
         *        Output:[-2,1,-2,4, 3,5,6,1,5]
         *        当前数数-2 那么最大值-2             (-2)
         *        下一个数1  -2+1<1 那么字串从1开始 1  (1)
         *               -3   -3+1>-3  字串 1 -3     (-2)
         *               4    -2+4<4   字串 4         (4)
         *               -1    4+-1>-1      4  -1      (3)
         *               2     3+2>2        4 -2 2      (5)
         *               1     5>1          4 -2 2 1     (6)
         *              -5     -5+6>-5      4  -2 2 1 -5  (1)
         *              4       1+4>4       4  -2 2 1 -5 4  (5)
         *               选择最大的一个数 6;
         */
        //时间复杂度o(n)空间0(n)
//        int [] help=new int[nums.length];
//        int max=nums[0];
//        help[0]=nums[0];
//        for (int i=1;i<nums.length;i++){
//            help[i]= Math.max(nums[i]+help[i-1],nums[i]);
//            max=max>help[i]?max:help[i];
//        }
//        return max;
        //时间复杂度o(n)空间0(1)
        int cur=nums[0];
        int sum=cur;
        for (int i=1;i<nums.length;i++){
          sum=sum>(cur = Math.max(nums[i],cur+nums[i])) ? sum:cur;
        }
        return sum;
    }

    public static void main(String[] args) {
        int []nums={-2,1,-3,4,-1,2,1,-5,4};
        System.out.println(maxSubArray(nums));
    }
}

猜你喜欢

转载自blog.csdn.net/yu0_zhang0/article/details/81917088
今日推荐