forked from Sunchit/Coding-Decoded
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMaxPairsWithKSum.java
47 lines (42 loc) · 1.09 KB
/
MaxPairsWithKSum.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
class Solution {
// TC: O(nlogn) SC: O(1)
public int maxOperations(int[] nums, int k) {
Arrays.sort(nums);
int start =0;
int end = nums.length-1;
int count = 0;
while(start<end){
int sum = nums[start]+ nums[end];
if(sum>k){
end--;
} else if(sum<k) {
start++;
} else{
// sum ==k
end--;
start++;
count++;
}
}
return count;
}
// TC: O(n) SC: O(n)
public int maxOperations(int[] nums, int k) {
Map<Integer, Integer> map =new HashMap<>();
int count =0;
for(int el: nums){
if(map.containsKey(k- el)){
int freq = map.get(k- el);
if(freq ==1){
map.remove(k-el);
} else {
map.put(k-el, freq-1);
}
count++;
} else{
map.put(el, map.getOrDefault(el, 0)+1);
}
}
return count;
}
}