KatInterview

Count Valid Sum Pairs

Greedy & IntervalsAuto-graded · 23 test cases
MediumAuto-gradedGreedy & Intervalstwo-pointersgreedysorting

Last updated

Tests greedy two-pointer technique on sorted arrays to maximize disjoint pairs meeting a sum condition.

You are given an array values containing n integers and an integer min_sum.

Your task is to form the maximum number of disjoint pairs from the array elements such that each pair (i, j) satisfies values[i] + values[j] >= min_sum. Each array element can be used in at most one pair.

Return the maximum number of valid pairs that can be formed.

Constraints

  • 0 <= n <= 10^5
  • -10^9 <= values[i] <= 10^9
  • -10^9 <= min_sum <= 10^9
  • Each element may be used at most once
  • If the array has an odd length, at least one element will remain unpaired

Examples

Example 1

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

Output: 2

Example 2

Input: count_valid_pairs([4, 4, 1, 1], 8)

Output: 1

Example 3

Input: count_valid_pairs([-10, -5, 0, 5, 10], 0)

Output: 2

Example 4

Input: count_valid_pairs([], 10)

Output: 0

Hints

Hint 1

Consider sorting the array first. How does ordering help identify which elements can potentially pair together?

Hint 2

Use a two-pointer approach with one pointer at each end of the sorted array. What does it mean if the sum of the smallest and largest remaining elements fails to meet the threshold?

Hint 3

If the smallest remaining element cannot pair with the largest remaining element, can it pair with any other element? This observation drives the greedy strategy.