KatInterview

Maximize Paired Sum with Coverage Constraint

Greedy & IntervalsAuto-graded · 19 test cases
HardAuto-gradedGreedy & Intervalsgreedysortingarrays

Last updated

Tests greedy reasoning and sorting to maximize the sum of "lesser" elements across a constrained pairing of an even-length array.

Problem

You are given an array of n integers, where n is always even. Your task is to partition all n elements into exactly n/2 pairs, then designate one element in each pair as the leader and the other as the supporter.

Within every pair, the supporter's value must be greater than or equal to the leader's value:

value[supporter] >= value[leader]

Each element belongs to exactly one pair and plays exactly one role.

The total score of a partition is the sum of all leaders' values:

score = sum of value[leader] over all pairs

Find the maximum possible total score across all valid ways to partition and assign roles.


Constraints

  • 2 <= n <= 2 * 10^5, and n is always even.
  • 1 <= values[i] <= 10^9
  • Your solution should run in significantly better than O(n^2) time.

Examples

Example 1

Input: max_paired_score([1, 2])

Output: 1

Example 2

Input: max_paired_score([1, 3, 2, 4])

Output: 4

Example 3

Input: max_paired_score([5, 5, 5, 5])

Output: 10

Hints

Hint 1

Notice that within any valid pair the leader is always the smaller of the two values — so you are really maximizing the sum of pair minimums.

Hint 2

Think about what happens when you sort the array. Which arrangement of pairs avoids "wasting" large values on leader slots that smaller values could fill just as well?

Hint 3

After sorting, try pairing up neighbors: (index 0, index 1), (index 2, index 3), and so on. The leader in each pair is the element at the even index. Can you convince yourself no other pairing can do better?