Maximum Sum With Specific Difference

You are given an array of integers and a number ‘K’. You can pair two elements in the array 'ARR' if the absolute difference between them is strictly less than ‘K’. Your task is to find the maximum possible sum of disjoint pairs among all the pairs of numbers you can obtain.

The sum of a pair is the sum of the elements in the pair.

For Example:
Input: ARR[] = {3, 5, 10, 15, 17, 12, 9}, K = 4
Output: 62

Then disjoint pairs with the absolute difference less than K are 
(3, 5), (10, 12), (15, 17)  
So maximum sum which we can get is 3 + 5 + 12 + 10 + 15 + 17 = 62
Note:
Note that an alternate way to form disjoint pairs is, (3, 5), (9, 12), (15, 17), but this pairing produces a lesser sum.
Input format:
The first line of input contains an integer ‘T’ denoting the number of test cases to run.

The first line of each test contains an integer 'N', denoting the size of the array 'ARR' which would be given.

The next line is the given array values in a space-separated set of ‘N’ elements.

The last line of every test case is s single integer denoting ‘K’.
Output format:
For every test case, you need to print the maximum possible sum of disjoint pairs. 

Output for each test case will be printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the given function.
Constraints:
1 <= T <= 100
1 <= N <= 3000
1 <= ARR[i] <=1000
1 <= K < 1000

Time limit: 1 sec
CodingNinjas
author
2y
Sorting

Approach: We sort the given array in increasing order. For every element, we try to pair it with its previous element first. Since the array is sorted, the value of ‘ARR[i]’ would be more than ...read more

CodingNinjas
author
2y
Optimized Sorting Approach

Approach: We can sort the array to ensure that every i’th and (i-1)st element is the closest possible pair. Now to get the maximum possible sum, we can iterate from largest t...read more

Help your peers!
Add answer anonymously...
American Express Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions
Get AmbitionBox app

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter