-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_1679.java
More file actions
49 lines (45 loc) · 1.41 KB
/
_1679.java
File metadata and controls
49 lines (45 loc) · 1.41 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
package com.github.aditya;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class _1679 {
class Solution {
// 20 ms, faster than 92.62%, memory 52 MB, less than 96.50%
// Time Complexity O(nlogn)
public int maxOperations(int[] nums, int k) {
int count = 0;
int left = 0, right = nums.length - 1;
Arrays.sort(nums);
while (left < right) {
int sum = nums[left] + nums[right];
if (k == sum) {
count++;
left++;
right--;
} else if (k < sum)
right--;
else
left++;
}
return count;
}
}
// 40 ms, faster than 47.96%, memory 54.1 MB, less than 83.69%
// Extra Space consumption because of HashMap
class Solution_1 {
public int maxOperations(int[] nums, int k) {
int count = 0;
Map<Integer, Integer> map = new HashMap<>();
for (int num : nums) {
int key = k - num;
if (map.containsKey(key) && (map.get(key) > 0)) {
map.put(key, map.get(key) - 1);
count++;
} else {
map.put(num, map.getOrDefault(num, 0) + 1);
}
}
return count;
}
}
}