-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathGFG003.cpp
More file actions
50 lines (37 loc) · 1.41 KB
/
GFG003.cpp
File metadata and controls
50 lines (37 loc) · 1.41 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
40
41
42
43
44
45
46
47
48
49
/*
Indexes of Subarray Sum
Given an array arr[] containing only non-negative integers, your task is to find a continuous subarray (a contiguous sequence of elements) whose sum equals a specified value target. You need to return the 1-based indices of the leftmost and rightmost elements of this subarray. You need to find the first subarray whose sum is equal to the target.
Note: If no such array is possible then, return [-1].
Examples:
Input: arr[] = [1, 2, 3, 7, 5], target = 12
Output: [2, 4]
Explanation: The sum of elements from 2nd to 4th position is 12.
Input: arr[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], target = 15
Output: [1, 5]
Explanation: The sum of elements from 1st to 5th position is 15.
Input: arr[] = [5, 3, 4], target = 2
Output: [-1]
Explanation: There is no subarray with sum 2.
*/
class Solution {
public:
vector<int> subarraySum(vector<int> &arr, int target) {
// code here
int left = 0, right = 0;
std::vector<int> result;
int sum = 0;
while (right < arr.size()) {
sum += arr[right];
while (sum > target && left <= right) {
sum -= arr[left];
left++;
}
if (sum == target) {
result = {left + 1, right + 1};
return result;
}
right++;
}
return {-1};
}
};