-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpairs_with_specific_difference.c
More file actions
84 lines (63 loc) · 1.38 KB
/
pairs_with_specific_difference.c
File metadata and controls
84 lines (63 loc) · 1.38 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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*
Pairs with Specific Difference Problem on GeeksForGeeks
Problem Link: https://practice.geeksforgeeks.org/problems/pairs-with-specific-difference/0
Note: This solution is NOT based on Dynamic Programming
Author: Shyam Kumar
*/
#include <stdio.h>
#include <stdlib.h>
int partition(int arr[], int p, int r) {
int i,j,x,temp;
i = p-1;
x = arr[r];
for(j = p; j <= r-1; j++) {
if(arr[j] <= x) {
i = i+1;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
temp = arr[i+1];
arr[i+1] = arr[r];
arr[r] = temp;
return i+1;
}
void quicksort(int arr[], int p, int r) {
int q;
if(p<r) {
q = partition(arr,p,r);
quicksort(arr,p,q-1);
quicksort(arr,q+1,r);
}
}
int pairs_specific_diff( int n, int *arr, int k ) {
int i, j, sum = 0;
quicksort( arr, 0, n-1 );
for( i = n-1; i >= 1; i-- ) {
if( arr[i] - arr[i-1] < k ) {
sum = sum + (arr[i] + arr[i-1]);
i--;
}
}
return sum;
}
int main(int argc, char const *argv[])
{
int i, n, k, ans, t;
printf("\nEnter the number of test casees:");
scanf("%d",&t);
while(t--) {
printf("Enter the value of N:");
scanf("%d",&n);
int *arr = (int*)malloc( 10000 * sizeof( int ) );
printf("\nEnter the array :");
for( i = 0; i < n; i++ )
scanf("%d",&arr[i]);
printf("\nEnter the value of k:");
scanf("%d",&k);
ans = pairs_specific_diff( n, arr, k );
printf("\nAns = %d", ans);
}
return 0;
}