-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfind_subarray_with_sum.cpp
More file actions
39 lines (34 loc) · 1.12 KB
/
find_subarray_with_sum.cpp
File metadata and controls
39 lines (34 loc) · 1.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
* Given an array A of non-negative numbers find a contiguous subarray elements of which sums up to a value X.
*/
#include "find_subarray_with_sum.hpp"
using namespace std;
typedef unsigned int uint;
optional<pair<size_t, size_t>> find_subarray_with_sum(vector<uint> const& values, uint target) {
if (values.empty()) {
return optional<pair<size_t, size_t>>();
}
size_t from_index = 0, to_index = 1;
auto sum = values[0];
while (from_index < values.size() && to_index <= values.size()) {
if (sum == target) {
return optional<pair<size_t, size_t>>(make_pair(from_index, to_index));
}
if (sum < target) {
to_index++;
if (to_index <= values.size()) {
sum += values[to_index - 1];
}
} else {
from_index++;
sum -= values[from_index - 1];
if (to_index <= from_index) {
to_index++;
if (from_index < values.size()) {
sum = values[from_index];
}
}
}
}
return optional<pair<size_t, size_t>>();
}