KatInterview

Count Disjoint Pairs That Add Up to a Goal Value

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashinghash-maptwo-pointersgreedy

Last updated

Find the most disjoint pairs in an integer list whose sum equals a goal, using value counts or sorting with two pointers, while handling duplicates, negatives and the half-goal case.

You are given a list of integers values and an integer goal.

In a single move you choose two different positions in the list whose elements add up to exactly goal, and you delete both of those elements. Deleted elements cannot be used again. Positions are what count, so two equal numbers at different positions are two separate elements, but one element can never be paired with itself.

Return the largest number of moves you can make.

Details

  • Moves may be made in any order, and the order has no effect on what is allowed. Only which elements end up paired matters.
  • Negative numbers and zero are ordinary values.
  • If the list has fewer than two elements, the answer is 0.
  • If goal is even, elements equal to goal / 2 pair with each other, which needs two separate elements per move.

Constraints

  • 0 <= len(values) <= 10^5
  • -10^9 <= values[i] <= 10^9
  • -2 * 10^9 <= goal <= 2 * 10^9
  • The function returns a single non-negative integer.

Examples

Example 1

Input: max_goal_pairs([1, 2, 3, 4], 5)

Output: 2

Example 2

Input: max_goal_pairs([3, 1, 3, 4, 3], 6)

Output: 1

Example 3

Input: max_goal_pairs([1, 1, 1, 1], 2)

Output: 2

Example 4

Input: max_goal_pairs([4, -1, 2, 7, -3, 6], 5)

Output: 1

Hints

Hint 1

A value x can only ever be paired with goal - x, so values split into independent groups that do not affect each other.

Hint 2

For two different partner values x and goal - x, the number of moves is limited by the smaller of their counts. When x equals goal - x, each move uses two copies, so think about integer halving of the count.

Hint 3

Scan once while keeping a map of unmatched values seen so far. Check for the partner before inserting the current value, so an element is never paired with itself. Alternatively, sort and move two pointers inward.