Sponsored
Sponsored
This approach involves using a hashmap to store the frequency of each number in the array. For each number in the array, check if the complement (k - current number) exists in the hashmap. If it does, form a pair and decrease the frequency of both the current number and its complement in the hashmap. This ensures that no number is reused in forming pairs, optimizing the number of operations possible.
Time Complexity: O(n) because it involves a single pass through the array and constant-time operations for the hash table.
Space Complexity: O(n) to store the counts in the hash map.
1import java.util.HashMap;
2
3class Solution {
4 public int maxOperations(int[] nums, int k) {
5 HashMap<Integer, Integer> map = new HashMap<>();
6 int operations = 0;
7 for (int num : nums) {
8 int complement = k - num;
9 if (map.getOrDefault(complement, 0) > 0) {
10 operations++;
11 map.put(complement, map.get(complement) - 1);
12 } else {
13 map.put(num, map.getOrDefault(num, 0) + 1);
14 }
15 }
16 return operations;
17 }
18
19 public static void main(String[] args) {
20 Solution sol = new Solution();
21 int[] nums = {1, 2, 3, 4};
22 int k = 5;
23 System.out.println(sol.maxOperations(nums, k));
24 }
25}
The Java solution uses a HashMap for counting frequencies. By iterating over the input array, it seeks complementary numbers in order to form k-pairs, updating the frequencies appropriately.
First sort the array, which allows the use of a two-pointer technique to find pairs. One pointer starts at the beginning and the other at the end of the sorted array. If the sum of the elements at these pointers equals k, increase the operations count and move both pointers. If the sum is less than k, move the left pointer to increase the sum, otherwise, move the right pointer to decrease the sum, thus efficiently finding all possible pairs.
Time Complexity: O(n log n) due to sorting, with a subsequent O(n) linear traversal using two pointers.
Space Complexity: O(1) for the additional pointers only.
This JavaScript technique uses Array.sort() for initial arrangement, benefiting the subsequent pointer mechanics by yielding effective pairings that reduce redundancy and optimize the maximal discoveries of sums.