1679. Max Number of K-Sum Pairs LeetCode Solution
In this guide, you will get 1679. Max Number of K-Sum Pairs LeetCode Solution with the best time and space complexity. The solution to Max Number of K-Sum Pairs problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.
Table of Contents
- Problem Statement
- Complexity Analysis
- Max Number of K-Sum Pairs solution in C++
- Max Number of K-Sum Pairs solution in Java
- Max Number of K-Sum Pairs solution in Python
- Additional Resources
Problem Statement of Max Number of K-Sum Pairs
You are given an integer array nums and an integer k.
In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.
Return the maximum number of operations you can perform on the array.
Example 1:
Input: nums = [1,2,3,4], k = 5
Output: 2
Explanation: Starting with nums = [1,2,3,4]:
– Remove numbers 1 and 4, then nums = [2,3]
– Remove numbers 2 and 3, then nums = []
There are no more pairs that sum up to 5, hence a total of 2 operations.
Example 2:
Input: nums = [3,1,3,4,3], k = 6
Output: 1
Explanation: Starting with nums = [3,1,3,4,3]:
– Remove the first two 3’s, then nums = [1,4,3]
There are no more pairs that sum up to 6, hence a total of 1 operation.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
1 <= k <= 109
Complexity Analysis
- Time Complexity: O(n)
- Space Complexity: O(n)
1679. Max Number of K-Sum Pairs LeetCode Solution in C++
class Solution {
public:
int maxOperations(vector<int>& nums, int k) {
int ans = 0;
unordered_map<int, int> count;
for (const int num : nums)
++count[num];
for (const auto& [num, freq] : count)
if (const auto it = count.find(k - num); it != count.end())
ans += min(freq, it->second);
return ans / 2;
}
};
/* code provided by PROGIEZ */
1679. Max Number of K-Sum Pairs LeetCode Solution in Java
class Solution {
public int maxOperations(int[] nums, int k) {
int ans = 0;
HashMap<Integer, Integer> count = new HashMap<>();
for (final int num : nums)
count.merge(num, 1, Integer::sum);
for (final int num : count.keySet()) {
final int complement = k - num;
if (count.containsKey(complement))
ans += Math.min(count.get(num), count.get(complement));
}
return ans / 2;
}
}
// code provided by PROGIEZ
1679. Max Number of K-Sum Pairs LeetCode Solution in Python
class Solution:
def maxOperations(self, nums: list[int], k: int) -> int:
count = collections.Counter(nums)
return sum(min(count[num], count[k - num])
for num in count) // 2
# code by PROGIEZ
Additional Resources
- Explore all LeetCode problem solutions at Progiez here
- Explore all problems on LeetCode website here
Happy Coding! Keep following PROGIEZ for more updates and solutions.