leetcode_question_53 Maximum Subarray

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.

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.

dp:

int maxSubArray(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int max = A[0];
        int currentsum = A[0];
        for(int i = 1; i < n; ++i){
            if(currentsum < 0) currentsum = 0;
            currentsum += A[i];
            if(currentsum > max) max = currentsum;
        }
        return max;
    }

Divide and Conquer:

int calmaxsubarr(int A[], int begin, int end){
        if(begin == end) return A[begin];
        
        int mid = (end-begin)/2 + begin;
        
        int left = calmaxsubarr(A, begin, mid);
        int right = calmaxsubarr(A, mid+1, end);
        
        int lefthalf = A[mid];
        int tmp = A[mid];
        for(int i = mid -1; i >= begin; i--){
            tmp += A[i];
            if(tmp > lefthalf) lefthalf = tmp;
        }
        
        int righthalf = A[mid+1];
        tmp = A[mid+1];
        for(int i = mid +2; i <= end; ++i){
            tmp += A[i];
            if(tmp > righthalf)righthalf = tmp;
        }
        int middle = lefthalf + righthalf;
        int res = left > right ? left : right;
        res = res > middle ? res : middle;
        return res;
    }
    int maxSubArray(int A[], int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return calmaxsubarr(A, 0, n-1);
    }




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值