Thursday, November 27, 2014

Maximum Subarray -- Leetcode 53

[Question]:
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.

[Analysis]:
Assume S[i] is the maximum sub-array which ends at A[i]. Then S[i] = max (S[i-1]+A[i], A[i]), i>0; S[0] = A[0]. The maximum of all S[i] is the result.  Time complexity is O(N).

Another solution is made by simple math.
[Solution]:
//-- DP--
class Solution {
public:
    int maxSubArray(int A[], int n) {
        assert(n>0);
     
        vector<int> sum(n, A[0]);
        for (int i=1; i<n; i++) {
            sum[i] = max (sum[i-1]+A[i], A[i]);
        }
        return *max_element( sum.begin(), sum.end() );
    }
};

//-- Running sum --
class Solution {
public:
    int maxSubArray(int A[], int n) {
        int ans=A[0],i,j,sum=0;
        for(i=0;i<n;i++){
            sum+=A[i];
            ans=max(sum,ans);
            sum=max(sum,0);
        }
        return ans;
    }
};

No comments:

Post a Comment