![]() |
VOOZH | about |
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:
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
Table of Content
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.
62
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.
62
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.
k, add both to sum and skip them Dry Run Example:
[3, 5, 10, 15, 17, 12, 9], k = 4[3, 5, 9, 10, 12, 15, 17], sum = 062