Sum of Pairs with Diff < k

Last Updated : 1 Jun, 2026

Given an array arr[] and an integer k, group the numbers into pairs to get maximum possible total sum of the pairs.

To form a valid pair, the following conditions must hold:

  • The absolute difference between the two numbers in the pair must be strictly less than k.
  • Pairs should be disjoint (each number from the array can only be used in a maximum of one pair).

Return the maximum possible total sum of the valid pairs.

Examples:

Input  : arr[] = [3, 5, 10, 15, 17, 12, 9], k = 4
Output : 62
Explanation: The disjoint pairs with difference less than k are, (3, 5), (10, 12), (15, 17), therefore maximum sum which we can get is 3 + 5 + 12 + 10 + 15 + 17 = 62. Note that an alternate way to form disjoint pairs is, (3, 5), (9, 12), (15, 17), but this pairing produces lesser sum.

Input  : arr[] = [5, 15, 10, 300], k = 12
Output : 25

Try It Yourself
redirect icon

[Naive Approach] Using Recursion – O(2^n) Time and O(n) Space

The idea is to try all possible ways of forming disjoint pairs using recursion. For each unused element, we either pair it with another valid element (whose difference is less than k) or skip it. We explore every possible combination and keep track of the maximum sum obtained. Since we are exploring all subsets of pairings, this guarantees the optimal answer but is highly inefficient.

  • Sort the array and maintain a visited array to track used elements
  • For each unused element, try pairing it with all valid unused elements and recurse
  • Also consider the option of skipping the current element and recurse
  • Track and return the maximum sum from all recursive possibilities
C++
#include <bits/stdc++.h>
using namespace std;

int solve(vector<int>& arr, vector<bool>& used, int k) {
    int n = arr.size();
    int maxSum = 0;

    for (int i = 0; i < n; i++) {
        if (used[i]) continue;

        // try pairing i with all j
        for (int j = i + 1; j < n; j++) {
            if (used[j]) continue;

            if (arr[j] - arr[i] < k) {
                used[i] = used[j] = true;

                maxSum = max(maxSum,
                             arr[i] + arr[j] + solve(arr, used, k));

                used[i] = used[j] = false;
            }
        }

        // option: skip i
        used[i] = true;
        maxSum = max(maxSum, solve(arr, used, k));
        used[i] = false;
        
        // only first unused i
        break; 
    }

    return maxSum;
}

int sumDiffPairs(vector<int>& arr, int k) {
    sort(arr.begin(), arr.end());
    vector<bool> used(arr.size(), false);
    return solve(arr, used, k);
}

int main() {
    vector<int> arr = {3, 5, 10, 15, 17, 12, 9};
    int k = 4;

    cout << sumDiffPairs(arr, k);
    return 0;
}
Java
import java.util.*;

class GFG {

    static int solve(int[] arr, boolean[] used, int k) {
        int n = arr.length;
        int maxSum = 0;

        for (int i = 0; i < n; i++) {
            if (used[i]) continue;

            // try pairing i with all j
            for (int j = i + 1; j < n; j++) {
                if (used[j]) continue;

                if (arr[j] - arr[i] < k) {
                    used[i] = used[j] = true;

                    maxSum = Math.max(maxSum,
                            arr[i] + arr[j] + solve(arr, used, k));

                    used[i] = used[j] = false;
                }
            }

            // option: skip i
            used[i] = true;
            maxSum = Math.max(maxSum, solve(arr, used, k));
            used[i] = false;

            // only first unused i
            break;
        }

        return maxSum;
    }

    static int sumDiffPairs(int[] arr, int k) {
        Arrays.sort(arr);
        boolean[] used = new boolean[arr.length];
        return solve(arr, used, k);
    }

    public static void main(String[] args) {
        int[] arr = {3, 5, 10, 15, 17, 12, 9};
        int k = 4;

        System.out.println(sumDiffPairs(arr, k));
    }
}
Python
def solve(arr, used, k):
    n = len(arr)
    maxSum = 0

    for i in range(n):
        if used[i]:
            continue

        # try pairing i with all j
        for j in range(i + 1, n):
            if used[j]:
                continue

            if arr[j] - arr[i] < k:
                used[i] = used[j] = True

                maxSum = max(maxSum,
                             arr[i] + arr[j] + solve(arr, used, k))

                used[i] = used[j] = False

        # option: skip i
        used[i] = True
        maxSum = max(maxSum, solve(arr, used, k))
        used[i] = False

        # only first unused i
        break

    return maxSum


def sumDiffPairs(arr, k):
    arr.sort()
    used = [False] * len(arr)
    return solve(arr, used, k)


if __name__ == "__main__":
    arr = [3, 5, 10, 15, 17, 12, 9]
    k = 4
    
    print(sumDiffPairs(arr, k))
C#
using System;

class GFG {

    static int Solve(int[] arr, bool[] used, int k) {
        int n = arr.Length;
        int maxSum = 0;

        for (int i = 0; i < n; i++) {
            if (used[i]) continue;

            // try pairing i with all j
            for (int j = i + 1; j < n; j++) {
                if (used[j]) continue;

                if (arr[j] - arr[i] < k) {
                    used[i] = used[j] = true;

                    maxSum = Math.Max(maxSum,
                        arr[i] + arr[j] + Solve(arr, used, k));

                    used[i] = used[j] = false;
                }
            }

            // option: skip i
            used[i] = true;
            maxSum = Math.Max(maxSum, Solve(arr, used, k));
            used[i] = false;

            // only first unused i
            break;
        }

        return maxSum;
    }
    
    static int sumDiffPairs(int[] arr, int k) {
        Array.Sort(arr);
        bool[] used = new bool[arr.Length];
        return Solve(arr, used, k);
    }

    public static void Main() {
        int[] arr = {3, 5, 10, 15, 17, 12, 9};
        int k = 4;

        Console.WriteLine(sumDiffPairs(arr, k));
    }
}
JavaScript
function solve(arr, used, k) {
    let n = arr.length;
    let maxSum = 0;

    for (let i = 0; i < n; i++) {
        if (used[i]) continue;

        // try pairing i with all j
        for (let j = i + 1; j < n; j++) {
            if (used[j]) continue;

            if (arr[j] - arr[i] < k) {
                used[i] = used[j] = true;

                maxSum = Math.max(maxSum,
                    arr[i] + arr[j] + solve(arr, used, k));

                used[i] = used[j] = false;
            }
        }

        // option: skip i
        used[i] = true;
        maxSum = Math.max(maxSum, solve(arr, used, k));
        used[i] = false;

        // only first unused i
        break;
    }

    return maxSum;
}

function sumDiffPairs(arr, k) {
    arr.sort((a, b) => a - b);
    let used = new Array(arr.length).fill(false);
    return solve(arr, used, k);
}

// Driver code
let arr = [3, 5, 10, 15, 17, 12, 9];
let k = 4;

console.log(sumDiffPairs(arr, k));

Output
62

[Better Approach] Using Dynamic Programming + Sorting – O(n log n) Time and O(n) Space

The idea is to first sort the array so that elements close in value come together, making it easier to form valid pairs with difference less than k. Then, we use dynamic programming where at each index we decide whether to include the current element in a pair with its previous element or skip it. This ensures that we form disjoint pairs while maximizing the total sum.

  • Sort the array to bring closer elements together for valid pairing
  • Use a DP array where each index stores the maximum sum possible till that point
  • At each index, either skip the element or form a pair with the previous element if difference < k
  • Take the maximum of both choices and return the last DP value
C++
#include <bits/stdc++.h>
using namespace std;

// method to return maximum sum we can get by
// finding less than k difference pair
int sumDiffPairs(vector<int> &arr, int k)
{
    // sort input array in ascending order.
    sort(arr.begin(), arr.end());

    int n = arr.size();

    // dp[i] denotes the maximum disjoint pair sum
    // we can achieve using first i elements
    vector<int> dp(n);

    // if no element then dp value will be 0
    dp[0] = 0;

    for (int i = 1; i < n; i++)
    {
        // first give previous value to dp[i] i.e.
        // no pairing with (i-1)th element
        dp[i] = dp[i-1];

        // if current and previous element can form a pair
        if (arr[i] - arr[i-1] < k)
        {
            // update dp[i] by choosing maximum between
            // pairing and not pairing
            if (i >= 2)
                dp[i] = max(dp[i], dp[i-2] + arr[i] + arr[i-1]);
            else
                dp[i] = max(dp[i], arr[i] + arr[i-1]);
        }
    }

    // last index will have the result
    return dp[n - 1];
}

int main()
{
    vector<int> arr = {3, 5, 10, 15, 17, 12, 9};
    int k = 4;

    cout << sumDiffPairs(arr, k);

    return 0;
}
Java
import java.util.*;

class GFG {

    // method to return maximum sum we can get by
    // finding less than k difference pair
    static int sumDiffPairs(int[] arr, int k)
    {
        // sort input array in ascending order.
        Arrays.sort(arr);

        int n = arr.length;

        // dp[i] denotes the maximum disjoint pair sum
        // we can achieve using first i elements
        int[] dp = new int[n];

        // if no element then dp value will be 0
        dp[0] = 0;

        for (int i = 1; i < n; i++)
        {
            // first give previous value to dp[i] i.e.
            // no pairing with (i-1)th element
            dp[i] = dp[i-1];

            // if current and previous element can form a pair
            if (arr[i] - arr[i-1] < k)
            {
                // update dp[i] by choosing maximum between
                // pairing and not pairing
                if (i >= 2)
                    dp[i] = Math.max(dp[i], dp[i-2] + arr[i] + arr[i-1]);
                else
                    dp[i] = Math.max(dp[i], arr[i] + arr[i-1]);
            }
        }

        // last index will have the result
        return dp[n - 1];
    }

    public static void main(String[] args)
    {
        int[] arr = {3, 5, 10, 15, 17, 12, 9};
        int k = 4;

        System.out.println(sumDiffPairs(arr, k));
    }
}
Python
# method to return maximum sum we can get by
# finding less than k difference pair
def sumDiffPairs(arr, k):

    # Sort input array in ascending order.
    arr.sort()

    n = len(arr)

    # dp[i] denotes the maximum disjoint pair sum
    # we can achieve using first i elements
    dp = [0] * n

    # if no element then dp value will be 0
    dp[0] = 0

    for i in range(1, n):

        # first give previous value to dp[i] i.e.
        # no pairing with (i-1)th element
        dp[i] = dp[i-1]

        # if current and previous element can form a pair
        if arr[i] - arr[i-1] < k:

            # update dp[i] by choosing maximum between
            # pairing and not pairing
            if i >= 2:
                dp[i] = max(dp[i], dp[i-2] + arr[i] + arr[i-1])
            else:
                dp[i] = max(dp[i], arr[i] + arr[i-1])

    # last index will have the result
    return dp[n - 1]


if __name__ == '__main__':
    arr = [3, 5, 10, 15, 17, 12, 9]
    k = 4
    
    print(sumDiffPairs(arr, k))
C#
using System;

class GFG {

    // method to return maximum sum we can get by
    // finding less than k difference pair
    static int sumDiffPairs(int[] arr, int k)
    {
        // Sort input array in ascending order.
        Array.Sort(arr);

        int n = arr.Length;

        // dp[i] denotes the maximum disjoint pair sum
        // we can achieve using first i elements
        int[] dp = new int[n];

        // if no element then dp value will be 0
        dp[0] = 0;

        for (int i = 1; i < n; i++)
        {
            // first give previous value to dp[i] i.e.
            // no pairing with (i-1)th element
            dp[i] = dp[i - 1];

            // if current and previous element can form a pair
            if (arr[i] - arr[i - 1] < k)
            {
                // update dp[i] by choosing maximum between
                // pairing and not pairing
                if (i >= 2)
                    dp[i] = Math.Max(dp[i], dp[i - 2] + arr[i] + arr[i - 1]);
                else
                    dp[i] = Math.Max(dp[i], arr[i] + arr[i - 1]);
            }
        }

        // last index will have the result
        return dp[n - 1];
    }

    public static void Main()
    {
        int[] arr = {3, 5, 10, 15, 17, 12, 9};
        int k = 4;

        Console.WriteLine(sumDiffPairs(arr, k));
    }
}
JavaScript
// method to return maximum sum we can get by
// finding less than k difference pair
function sumDiffPairs(arr, k)
{
    // Sort input array in ascending order.
    arr.sort((a, b) => a - b);

    let n = arr.length;

    // dp[i] denotes the maximum disjoint pair sum
    // we can achieve using first i elements
    let dp = new Array(n).fill(0);

    // if no element then dp value will be 0
    dp[0] = 0;

    for (let i = 1; i < n; i++)
    {
        // first give previous value to dp[i] i.e.
        // no pairing with (i-1)th element
        dp[i] = dp[i-1];

        // if current and previous element can form a pair
        if (arr[i] - arr[i-1] < k)
        {
            // update dp[i] by choosing maximum between
            // pairing and not pairing
            if (i >= 2)
                dp[i] = Math.max(dp[i], dp[i-2] + arr[i] + arr[i-1]);
            else
                dp[i] = Math.max(dp[i], arr[i] + arr[i-1]);
        }
    }

    // last index will have the result
    return dp[n - 1];
}

// Driver code
let arr = [3, 5, 10, 15, 17, 12, 9];
let k = 4;

console.log(sumDiffPairs(arr, k));

Output
62

[Expected Approach] Using Greedy – O(n log n) Time and O(1) Space

The idea is to maximize the sum by always picking the largest possible valid pair first. After sorting the array, we iterate from the end so that bigger elements are considered first. If two consecutive elements have a difference less than k, we pair them and add their sum. Since larger numbers contribute more to the total, this greedy choice ensures a maximum sum while keeping pairs disjoint.

  • Sort the array in ascending order
  • Traverse from the end to prioritize larger elements
  • If the difference between current and previous element is less than k, add both to sum and skip them
  • Continue until all elements are processed and return the total sum

Dry Run Example:

  • Initial array: [3, 5, 10, 15, 17, 12, 9], k = 4
  • Sorted array: [3, 5, 9, 10, 12, 15, 17], sum = 0
  • i = 6 : Compare 17 and 15 (Diff: 2 < 4) → Valid! add 32 (sum = 32), skip 15, move i to 4.
  • i = 4 : Compare 12 and 10 (Diff: 2 < 4) → Valid! add 22 (sum = 54), skip 10, move i to 2.
  • i = 2 : Compare 9 and 5 (Diff: 4 is not < 4) → Invalid, add nothing, move i to 1.
  • i = 1 : Compare 5 and 3 (Diff: 2 < 4) → Valid! add 8 (sum = 62), skip 3, loop ends.
    Final Maximum Sum: 62
C++
#include <bits/stdc++.h>
using namespace std;

// Method to return maximum sum we can get by
// finding less than k difference pairs
int sumDiffPairs(vector<int> &arr, int k)
{
    int maxSum = 0;

    // Sort elements to ensure every i and i-1 is closest
    // possible pair
    sort(arr.begin(), arr.end());

    int n = arr.size();

    // To get maximum possible sum, 
    // iterate from largest to
    // smallest, giving larger 
    // numbers priority over smaller
    // numbers.
    for (int i = n - 1; i > 0; --i) 
    {
        // Case I: Diff of arr[i] and arr[i-1]
        // is less than K, add to maxSum       
        // Case II: Diff between arr[i] and arr[i-1] is not
        // less than K, move to next i
        if (arr[i] - arr[i - 1] < k)
        {
            // Assuming only positive numbers.
            maxSum += arr[i];
            maxSum += arr[i - 1];

            // When a match is found skip this pair
            --i;
        }
    }

    return maxSum;
}

int main()
{
    vector<int> arr = { 3, 5, 10, 15, 17, 12, 9 };
    int k = 4;

    cout << sumDiffPairs(arr, k);
    return 0;
}
Java
import java.util.*;

class GFG {

    // method to return maximum sum we can get by
    // finding less than k difference pairs
    static int sumDiffPairs(int[] arr, int k)
    {
        int maxSum = 0;

        // Sort elements to ensure every i and i-1 is closest
        // possible pair
        Arrays.sort(arr);

        int n = arr.length;

        // To get maximum possible sum, 
        // iterate from largest to
        // smallest, giving larger 
        // numbers priority over smaller
        // numbers.
        for (int i = n - 1; i > 0; --i) 
        {
            // Case I: Diff of arr[i] and arr[i-1]
            // is less than K, add to maxSum       
            // Case II: Diff between arr[i] and arr[i-1] is not
            // less than K, move to next i
            if (arr[i] - arr[i - 1] < k)
            {
                // Assuming only positive numbers.
                maxSum += arr[i];
                maxSum += arr[i - 1];

                // When a match is found skip this pair
                --i;
            }
        }

        return maxSum;
    }

    public static void main(String[] args)
    {
        int[] arr = {3, 5, 10, 15, 17, 12, 9};
        int k = 4;

        System.out.println(sumDiffPairs(arr, k));
    }
}
Python
# Method to return maximum sum we can get by
# finding less than k difference pairs
def sumDiffPairs(arr, k):

    maxSum = 0

    # Sort elements to ensure every i and i-1 is closest
    # possible pair
    arr.sort()

    n = len(arr)

    # To get maximum possible sum, 
    # iterate from largest to
    # smallest, giving larger 
    # numbers priority over smaller
    # numbers.
    i = n - 1
    while i > 0:

        # Case I: Diff of arr[i] and arr[i-1]
        # is less than K, add to maxSum       
        # Case II: Diff between arr[i] and arr[i-1] is not
        # less than K, move to next i
        if arr[i] - arr[i - 1] < k:

            # Assuming only positive numbers.
            maxSum += arr[i]
            maxSum += arr[i - 1]

            # When a match is found skip this pair
            i -= 2
        else:
            i -= 1

    return maxSum


if __name__ == '__main__':
    arr = [3, 5, 10, 15, 17, 12, 9]
    k = 4
    
    print(sumDiffPairs(arr, k))
C#
using System;

class GFG {

    // Method to return maximum sum we can get by
    // finding less than k difference pairs
    static int sumDiffPairs(int[] arr, int k)
    {
        int maxSum = 0;

        // Sort elements to ensure every i and i-1 is closest
        // possible pair
        Array.Sort(arr);

        int n = arr.Length;

        // To get maximum possible sum, 
        // iterate from largest to
        // smallest, giving larger 
        // numbers priority over smaller
        // numbers.
        for (int i = n - 1; i > 0; --i) 
        {
            // Case I: Diff of arr[i] and arr[i-1]
            // is less than K, add to maxSum       
            // Case II: Diff between arr[i] and arr[i-1] is not
            // less than K, move to next i
            if (arr[i] - arr[i - 1] < k)
            {
                // Assuming only positive numbers.
                maxSum += arr[i];
                maxSum += arr[i - 1];

                // When a match is found skip this pair
                --i;
            }
        }

        return maxSum;
    }

    public static void Main()
    {
        int[] arr = {3, 5, 10, 15, 17, 12, 9};
        int k = 4;

        Console.WriteLine(sumDiffPairs(arr, k));
    }
}
JavaScript
// Method to return maximum sum we can get by
// finding less than k difference pairs
function sumDiffPairs(arr, k)
{
    let maxSum = 0;

    // Sort elements to ensure every i and i-1 is closest
    // possible pair
    arr.sort((a, b) => a - b);

    let n = arr.length;

    // To get maximum possible sum, 
    // iterate from largest to
    // smallest, giving larger 
    // numbers priority over smaller
    // numbers.
    for (let i = n - 1; i > 0; --i) 
    {
        // Case I: Diff of arr[i] and arr[i-1]
        // is less than K, add to maxSum       
        // Case II: Diff between arr[i] and arr[i-1] is not
        // less than K, move to next i
        if (arr[i] - arr[i - 1] < k)
        {
            // Assuming only positive numbers.
            maxSum += arr[i];
            maxSum += arr[i - 1];

            // When a match is found skip this pair
            --i;
        }
    }

    return maxSum;
}

// Driver code
let arr = [3, 5, 10, 15, 17, 12, 9];
let k = 4;

console.log(sumDiffPairs(arr, k));

Output
62
Comment