-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsubarray_sum.c
More file actions
50 lines (42 loc) · 1014 Bytes
/
subarray_sum.c
File metadata and controls
50 lines (42 loc) · 1014 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
49
50
//Geeks For Geeks - Subarray with given sum
//Correct on this machine but not on GFG's machine
#include <stdio.h>
#include <stdlib.h>
void subarray_sum( int *arr, int n, int *start, int *end, int r_sum ) {
int i, j, sum = 0;
for( i = 0; i < n-1; i++ ) {
sum = 0;
j = i;
while( sum <= r_sum && j <= n ) {
if( sum == r_sum ) {
*start = i+1;
*end = j;
return;
}
sum += arr[j++];
}
}
return;
}
int main(void) {
int t, n, r_sum, start = 0, end = 0, i, j;
printf("\nEnter the number of test cases:");
scanf("%d",&t);
for(i = 0; i < t; i++) {
printf("\nEnter the value of n:");
scanf("%d",&n);
printf("\nEnter the required sum:");
scanf("%d",&r_sum);
int *arr = (int*)malloc(sizeof(int) * n);
printf("\nEnter the array:");
for(j = 0; j < n; j++)
scanf("%d",&arr[j]);
subarray_sum( arr, n, &start, &end, r_sum );
if( start == 0 && end == 0)
printf("\nAnswer: -1");
else {
printf("\nAnswer: start = %d end = %d", start, end);
}
}
return 0;
}