Maximum sum of pairs with specific difference

Pattern: 1D DP

medium

Form disjoint pairs whose difference is less than k, maximising the total of the paired values. Sort first; then pairing neighbours is always enough, and best(i) = max(best(i-1), best(i-2) + a[i-1] + a[i-2] if they differ by less than k).

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Pair up elements (each used at most once) so that every pair's difference is less than k, and return the largest total of all paired elements. [3, 5, 10, 15, 17, 12, 9], k = 4 gives 62. The catalogue has no practice link for this one.

Think first

  • After sorting, which partners are worth considering?
  • What are the two choices for the largest element?
  • Why does pairing neighbours never lose?

Hints

    Brute force, and why it fails

    Try every pairing: exponential.

    The key insight

    Sorted, the best pairing uses only neighbouring pairs, which a 1D DP picks.

    Dry run

    sorted3 5 9 10 12 15 17

    arr [3, 5, 10, 15, 17, 12, 9], k = 4. Sorted: 3, 5, 9, 10, 12, 15, 17.

    Step 1 of 3

    The plan

    sort; best[i] = best[i-1]; if a[i-1] - a[i-2] < k: best[i] = max(best[i], best[i-2] + a[i-1] + a[i-2])
    

    Complexity

    Time
    O(n log n)
    Space
    O(n)

    Sorting dominates.

    Edge cases

    • No valid pair: 0.
    • One element: 0.
    • All equal: every pair counts.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int maxSumPairWithDifferenceLessThanK(int[] arr, int k) {
            int[] a = arr.clone();
            Arrays.sort(a);                         // after sorting, a best pairing only pairs neighbours
            int n = a.length;
            int[] best = new int[n + 1];            // best[i]: the most from the first i values
            for (int i = 2; i <= n; i++) {
                best[i] = best[i - 1];              // a[i - 1] stays unpaired
                if (a[i - 1] - a[i - 2] < k) best[i] = Math.max(best[i], best[i - 2] + a[i - 1] + a[i - 2]);   // or pairs with a[i - 2]
            }
            return best[n];
        }
    }

    C++

    class Solution {
    public:
        int maxSumPairWithDifferenceLessThanK(vector<int>& arr, int k) {
            vector<int> a(arr);
            sort(a.begin(), a.end());               // after sorting, a best pairing only pairs neighbours
            int n = static_cast<int>(a.size());
            vector<int> best(n + 1, 0);             // best[i]: the most from the first i values
            for (int i = 2; i <= n; i++) {
                best[i] = best[i - 1];              // a[i - 1] stays unpaired
                if (a[i - 1] - a[i - 2] < k) best[i] = max(best[i], best[i - 2] + a[i - 1] + a[i - 2]);   // or pairs with a[i - 2]
            }
            return best[n];
        }
    };

    Python

    class Solution:
        def maxSumPairWithDifferenceLessThanK(self, arr: list[int], k: int) -> int:
            a = sorted(arr)                         # after sorting, a best pairing only pairs neighbours
            best = [0] * (len(a) + 1)               # best[i]: the most from the first i values
            for i in range(2, len(a) + 1):
                best[i] = best[i - 1]               # a[i - 1] stays unpaired
                if a[i - 1] - a[i - 2] < k:
                    best[i] = max(best[i], best[i - 2] + a[i - 1] + a[i - 2])   # or pairs with a[i - 2]
            return best[-1]

    Common mistakes

    • Using <= k instead of < k.
    • Not sorting first.

    Similar problems