-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathProblem-2.java
81 lines (55 loc) · 1.73 KB
/
Problem-2.java
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
/**
* @author AkashGoyal
* @date 28/05/2021
*/
/**
--------------------- Problem----------->> Count pairs with given sum
Problem Link :- https://practice.geeksforgeeks.org/problems/count-pairs-with-given-sum5022/1
Reference:- https://www.youtube.com/watch?v=bvKMZXc0jQU
*/
class Solution {
int getPairsCount(int[] arr, int n, int k) {
// code here
int pair_count=0;
HashMap<Integer,Integer> hs=new HashMap<>();
for(int i=0;i<n;i++)
{
if(!hs.containsKey(arr[i]))
{
hs.put(arr[i],1);
}
else
{
int count=hs.get(arr[i]);
count++;
hs.put(arr[i],count);
}
}
for(Integer key: hs.keySet())
{
if(hs.containsKey(k-key))
{
pair_count+=hs.get(key)*hs.get(k-key); //
}
}
if(k%2==0 && hs.containsKey(k/2))
{
if(hs.get(k/2)>1)
{
//removing already considered k/2 term .
pair_count-=hs.get(k/2)*hs.get(k/2);
}
}
//dividing pair count because pairs have been considered twice-->> (n,k-n), (k-n,n)
pair_count=pair_count/2 ;
if(k%2==0 && hs.containsKey(k/2))
{
if(hs.get(k/2)>1)
{
//adding no of pairs of k/2
pair_count+= ((hs.get(k/2)*(hs.get(k/2)-1)))/2;
}
}
return pair_count;
}
}