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 <iostream>
2#include <unordered_map>
3#include <vector>
4
5int maxOperations(std::vector<int>& nums, int k) {
6 std::unordered_map<int, int> hashmap;
7 int operations = 0;
8 for (int num : nums) {
9 int complement = k - num;
10 if (hashmap[complement] > 0) {
11 operations++;
12 hashmap[complement]--;
13 } else {
14 hashmap[num]++;
15 }
16 }
17 return operations;
18}
19
20int main() {
21 std::vector<int> nums = {1, 2, 3, 4};
22 int k = 5;
23 std::cout << maxOperations(nums, k) << std::endl;
24 return 0;
25}
The C++ solution uses an unordered_map to count the occurrences of each number. It efficiently checks for a complement to form valid pairs and decrements their counts when pairs are formed, thus avoiding reuse.
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.
The Java approach sorts the input array and utilizes two pointers to systematically find and count all feasible pairs, capitalizing on already established sorted positioning for efficient comparisons.