Maximum Sum of Disjoint Pairs with Specific Difference

Given an array of integers and a number K, your task is to form pairs of elements from the array such that the absolute difference between them is strictly less than K, and the sum of these disjoint pairs is maximized.

Explanation:

The sum of a pair is the sum of its two elements. You need to find the maximum possible sum of all such disjoint pairs that can be formed.

Input:

T
N
ARR[]
K

Output:

Maximum sum of disjoint pairs for each test case in a new line.

Example:

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

Disjoint pairs with differences less than K are (3, 5), (10, 12), and (15, 17). Their maximum sum is 3 + 5 + 10 + 12 + 15 + 17 = 62.

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 3000
  • 1 <= ARR[i] <= 1000
  • 1 <= K < 1000
  • Time limit: 1 sec
Note:
Multiple ways to form disjoint pairs are possible, but the sum should be maximized.
AnswerBot
4mo

Find maximum sum of disjoint pairs with specific difference in an array.

  • Sort the array in non-decreasing order.

  • Iterate through the array and form pairs with absolute difference less than K.

  • Keep track ...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Intern Interview Questions Asked at ACKO

Q. Given the root of a binary tree, traverse the tree using inorder, preorder, and ...read more
Q. How would you design an application like Instagram?
Q. Rat in a Maze Problem Statement Given a maze of size N * N with a rat placed at ...read more
Software Developer Intern Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits