-
-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathFind Subarray with given sum
More file actions
48 lines (42 loc) · 971 Bytes
/
Find Subarray with given sum
File metadata and controls
48 lines (42 loc) · 971 Bytes
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
/* A simple program to print subarray
with sum as given sum */
#include <bits/stdc++.h>
using namespace std;
/* Returns true if the there is a subarray
of arr[] with sum equal to 'sum' otherwise
returns false. Also, prints the result */
void subArraySum(int arr[], int n, int sum)
{
// Pick a starting point
for (int i = 0; i < n; i++) {
int currentSum = arr[i];
if (currentSum == sum) {
cout << "Sum found at indexes " << i << endl;
return;
}
else {
// Try all subarrays starting with 'i'
for (int j = i + 1; j < n; j++) {
currentSum += arr[j];
if (currentSum == sum) {
cout << "Sum found between indexes "
<< i << " and " << j << endl;
return;
}
}
}
}
cout << "No subarray found";
return;
}
// Driver Code
int main()
{
int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 };
int n = sizeof(arr) / sizeof(arr[0]);
int sum = 23;
subArraySum(arr, n, sum);
return 0;
}
// This code is contributed
// by rathbhupendra