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.
1#include <stdio.h>
2#include <stdlib.h>
3#include <string.h>
4
5#define MAX 100000
6
7int maxOperations(int* nums, int numsSize, int k) {
8 int hash[MAX] = {0}, operations = 0;
9 for (int i = 0; i < numsSize; i++) {
10 int complement = k - nums[i];
11 if (complement >= 0 && hash[complement] > 0) {
12 operations++;
13 hash[complement]--;
14 } else {
15 hash[nums[i]]++;
16 }
17 }
18 return operations;
19}
20
21int main() {
22 int nums[] = {1, 2, 3, 4};
23 int size = sizeof(nums) / sizeof(nums[0]);
24 int k = 5;
25 printf("%d\n", maxOperations(nums, size, k));
26 return 0;
27}
The C solution utilizes a fixed-size array to simulate a hashmap because the constraints allow it. It iterates over all elements while checking if the complement needed to make up k exists in the hashmap. If it does, a pair is formed, and the operations count is increased.
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.