-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubArrayWithGivenSum.cpp
More file actions
43 lines (37 loc) · 1019 Bytes
/
subArrayWithGivenSum.cpp
File metadata and controls
43 lines (37 loc) · 1019 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
//https://practice.geeksforgeeks.org/problems/subarray-with-given-sum/0
//solution for the above problem
#include <bits/stdc++.h>
using namespace std;
int subArraySum(int arr[], int n, int sum)
{
int curr_sum, i, j;
// Pick a starting point
for (i = 0; i < n; i++)
{
curr_sum = arr[i];
// try all subarrays starting with 'i'
for (j = i + 1; j <= n; j++)
{
if (curr_sum == sum)
{
cout << "Sum found between indexes "
<< i << " and " << j - 1;
return 1;
}
if (curr_sum > sum || j == n)
break;
curr_sum = curr_sum + arr[j];
}
}
cout << "No subarray found";
return 0;
}
// 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;
}