Max Number of K-Sum Pairs LeetCode solution in Java

1
class Solution {
2
public int maxOperations(int[] nums, int k) {
3
HashMap<Integer, Integer> map = new HashMap<>();
4
int count = 0;
5
for (int i = 0; i < nums.length; i++) {
6
// to check if that k-nums[i] present and had some value left or already paired
7
if (map.containsKey(k - nums[i]) && map.get(k - nums[i]) > 0) {
8
count++;
9
map.put(k - nums[i], map.get(k - nums[i]) - 1);
10
} else {
11
// getOrDefault is easy way it directly checks if value is 0 returns 0 where I added 1
12
// and if some value is present then it return that value "similar to map.get(i)" and I
13
// added 1 on it
14
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
15
}
16
}
17
return count;
18
}
19
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0