-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path18. Max Number of K-Sum Pairs
52 lines (45 loc) · 1.2 KB
/
18. Max Number of K-Sum Pairs
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
class Solution {
public int maxOperations(int[] nums, int k) {
Map<Integer,Integer> map=new HashMap<>();
for(int i:nums){
map.put(i,map.getOrDefault(i,0)+1);
}
int count=0;
for(int i:map.keySet()){
if(map.containsKey(i) && map.containsKey(k-i)){
if(i!=k-i){
count+=Math.min(map.get(i),map.get(k-i));
map.put(i,0);
map.put(k-i,0);
}
else{
count+=Math.floor(map.get(i)/2);
map.put(i,0);
}
}
}
return count;
}
}
class Solution {
public int maxOperations(int[] nums, int k) {
Arrays.sort(nums);
int left=0,right=nums.length-1;
int count=0;
while(left<right){
int sum=nums[left]+nums[right];
if(sum==k){
left++;
right--;
count++;
}
else if(sum>k){
right--;
}
else{
left++;
}
}
return count;
}
}