<AI/>
enru
Все статьи

Max number of K-sum pairs

LeetCode 1679: Count the maximum number of operations removing pairs of numbers that sum up to k.

Сложность
Средняя
Опубликовано
Темы
#array#hash table
Открыть на LeetCode

Статья пока доступна только на английском.

Problem Description

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.

Constraints

  • The array length is in the range from 1 to 105
  • Each element is in the range from 1 to 109
  • k is in the range from 1 to 109

Examples

Input: nums = [1,2,3,4], k = 5

Answer: 2

Explanation: You can remove two pairs of numbers, (1,4) and (2,3), each summing to 5.

Solution

We create a hash table digits that stores the frequency of each number from the array.

We loop over all elements and for each number compute the difference diff between k and the current number num.

If digits already has an entry for diff, it means we have previously seen a number that together with the current num sums to k. In that case we decrement the number of available diff values by one and increment the pair counter res, since we've found a new pair.

Otherwise, we add the current number num to digits, incrementing its counter by one, so that it can be paired with another number later.

This way the function checks every number in turn, trying to form pairs, and returns the total number of pairs that sum up to k.

typescript
export const maxOperations = (nums: number[], k: number): number => {
  const digits: Record<number, number> = {};
  let res = 0;
 
  for (const num of nums) {
    const diff = k - num;
 
    if (digits[diff] > 0) {
      digits[diff] = (digits[diff] || 0) - 1;
      res++;
    } else {
      digits[num] = (digits[num] || 0) + 1;
    }
  }
 
  return res;
};

Complexity Analysis

Time Complexity

O(n), since we iterate over all elements of the array.

Space Complexity

O(n), since we create a hash table to store the frequencies.