#1679

Max Number of K-Sum Pairs

Medium HashMap pairing

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

In one operation you remove two numbers that sum to k. Return the most operations you can do.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: how many disjoint pairs sum to k?

Why this works: keep numbers waiting for a partner; when x arrives and k - x is waiting, use it up.

Example: [3, 1, 3, 4, 3], k = 6

3 waits, 1 waits3 pairs with 3 → 1 op4 waits, 3 waits → answer 1

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Counting x with itself when x = k − x and only one copy is available — checking before storing x avoids it.

Solve on LeetCode ↗
Complexity
  • Time: O(n).
  • Space: O(n).
Topic: Hashing
🎬 Episodes 37–39: video coming soon