首页 > 代码库 > LeetCode: Maximum Subarray [052]

LeetCode: Maximum Subarray [052]

【题目】


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.



【题意】

给定一个数组,找出和最大的子数组,返回这个最大和


【思路】

之前去搜狗面试的时候被问到过这道题,典型的DP问题
从后向前依次确定以每一位开头的最大子串和
用A[i]表示i位置上的值,maxSum[i]表示i位置开头的最大子串的和
如果maxSum[i+1]<0,则maxSum[i]=A[i];
如果maxSum[i+1]>=0, 则maxSum[i]=A[i]+maxSum[i+1];


【代码】

class Solution {
public:
    int maxSubArray(int A[], int n) {
        if(n==0)return 0;
        if(n==1)return A[0];
        int max=A[n-1];
        int*maxSum=new int[n];
        maxSum[n-1]=A[n-1];
        for(int i=n-2; i>=0; i--){
            if(maxSum[i+1]<0)maxSum[i]=A[i];
            else maxSum[i]=A[i]+maxSum[i+1];
            if(maxSum[i]>max)max=maxSum[i];
        }
        return max;
    }
};