LeetCode - Array - 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.

class Solution {
public:
    int maxSubArray(int A[], int n) {
        if(A==NULL)
            return 0;
        int result=INT_MIN,temp=0;
        for(int i=0;i<n;i++)
        {
            temp+=A[i];
            result=max(temp,result);
            if(temp<0)
                temp=0;
        }
        return result;
    }
};


class Solution {
public:
    int maxSubArray(int A[], int n) {
        if(A==NULL)
            return 0;
        maxSub(A, 0, n-1);
        
    }
    int maxSub(int A[], int b, int e)
    {
        if(b==e)
            return A[b];
        if(b+1==e)
            return max(max(A[b],A[e]),A[b]+A[e]);
        int mid=(b+e)/2;
        int maxLeft=maxSub(A, b, mid-1);
        int maxRight=maxSub(A,mid+1,e);
        int maxMid;
        int maxMidLeft=INT_MIN,maxMidRight=INT_MIN;
        int maxTemp1=0,maxTemp2=0;
        for(int i=mid;i>=0;i--)
        {
            maxTemp1+=A[i];
            maxMidLeft=max(maxMidLeft,maxTemp1);
        }
        for(int i=mid;i<=e;i++)
        {
            maxTemp2+=A[i];
            maxMidRight=max(maxMidRight, maxTemp2);
        }
        maxMid=maxMidRight+maxMidLeft-A[mid];
        return max(max(maxLeft,maxMid),maxRight);
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值