The largest sum of the subarray that no more than K

Given an array of integers A and an integer k, 
find a subarray that contains the largest sum, 
subject to a constraint that the sum is less than k?
vector vec = {3,4,1,2,4,1,-5}; 
int k = 0;

int main() {
    set seq;

    int sum = 0;
    int res = INT_MIN;

    for (auto e : vec) {
        sum += e;
        auto iter = seq.lower_bound(sum - k); 
        if (iter != seq.end()) {
            res = max(res, sum - *iter); 
        }
        seq.emplace(sum); 
    }
    cout << res << endl;
    return 0;
}

你可能感兴趣的:(算法)