-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pairs with specific difference .txt
46 lines (46 loc) · 1.14 KB
/
Pairs with specific difference .txt
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
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main (String[] args) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
StringBuffer sb=new StringBuffer();
int T=Integer.parseInt(br.readLine());
while(T-->0)
{
int n=Integer.parseInt(br.readLine());
String[] s=br.readLine().split("\\s");
int k=Integer.parseInt(br.readLine());
int[] arr=new int[n];
int[] dp=new int[n+1];
Arrays.fill(dp,-1);
for(int i=0;i<n;i++)
{
arr[i]=Integer.parseInt(s[i]);
}
Arrays.sort(arr);
sb.append(pairsum(arr,0,k,dp)+"\n");
}
System.out.print(sb);
}
public static int pairsum(int[] arr,int i,int k,int[] dp)
{
if(i+1>=arr.length)
{
return 0;
}
if(dp[i]!=-1)
{
return dp[i];
}
int smallans1=0,smallans2=0;
if(arr[i+1]-arr[i]<k)
{
smallans1=arr[i+1]+arr[i]+pairsum(arr,i+2,k,dp);
}
smallans2=pairsum(arr,i+1,k,dp);
return dp[i]=Math.max(smallans1,smallans2);
}
}