LeetCode 53. Maximum Subarray

题意:找出一个数组中某一段累加和最大

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.

一看到题目,这不就是算法导论的股票问题么...好吧,按着分治策略写,写着写着发现还是有点麻烦啊。。。虽然思想不难,这就是个easy题为啥这么难。。。然后就没考虑用分治,反正也就O(n),一次循环找最大也可以啊,代码如下:

class Solution {
    public int maxSubArray(int[] nums) {
        int result = nums[0], sum = nums[0];
        for (int i = 1; i < nums.length; i++){
            sum = Math.max(sum + nums[i], nums[i]);//决定是当前位置(nums[i])还是累加值(sum + nums[i]),即不停的寻找最大的新值,方法是如果前面的累加还不如新出现的值大,那肯定选择新出现的值;如果累加的大那就继续累加。
            result = Math.max(result, sum);//决定目前的最大值(sum)还是之前的最大值(result),即我累加但不一定有以前的好,因为有可能加了一个负的数,那要有一个保存之前最大值的数。
        }
        return result;
    }
}

好的,然后偷偷瞄了下discussion的分治答案,果然写的很好- -

class Solution {
    public int maxSubArray(int A[], int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        if(n==0) return 0;
        return maxSubArrayHelperFunction(A,0,n-1);
    }
    
    private int maxSubArrayHelperFunction(int A[], int left, int right) {
        if(right == left) return A[left];
        int middle = (left+right)/2;
        int leftans = maxSubArrayHelperFunction(A, left, middle);
        int rightans = maxSubArrayHelperFunction(A, middle+1, right);
        int leftmax = A[middle];
        int rightmax = A[middle+1];
        int temp = 0;
        for(int i=middle;i>=left;i--) {
            temp += A[i];
            if(temp > leftmax) leftmax = temp;
        }
        temp = 0;
        for(int i=middle+1;i<=right;i++) {
            temp += A[i];
            if(temp > rightmax) rightmax = temp;
        }
        return max(max(leftans, rightans),leftmax+rightmax);
    }
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值