Thursday, November 27, 2014

Total of Subarray

[Question]
Given an array A of numbers and a target number N, check if there is a contiguous sequence in array which sums to the target N.

[Analysis]
To match a target number, the best way is to use hash-table. The sum of contiguous sub-array Sum[i,j] = Sum[0,j] - Sum[0, i-1]. Assume all Sum[0, i] , N needs to be the difference of  Sum[0, k] and Sum[0, l]. Time complexity is O(N).

[Solution]
bool maxOfSubArray ( vector<int> vec, int target ) {
    vector<int> sum (vec.size(), vec[0]);
    for (int i=1; i<vec.size(); i++)
         sum[i] =sum[i-1]+vec[i];
 
    unordered_set<int> sum_set ( sum.begin(), sum.end() );
    for (auto s: sum_set) {
        if ( sum_set.find(s+target) != sum_set.end() )
             return true;
    }
    return false;
}

No comments:

Post a Comment