![]() |
VOOZH | about |
Given an array arr[] of n integers and an integer target, the task is to find a quadruplet in arr[] whose sum is closest to target.
Note: There may be multiple quadruplets with sum closest to the target, return any one of them.
Examples:
Input: arr[] = {4, 5, 3, 4, 1, 2}, target = 13
Output: {4, 5, 3, 1}
Explanation:
Sum of quadruplets:
4 + 5 + 3 + 4 = 16
4 + 5 + 3 + 1 = 13
4 + 5 + 3 + 2 = 14
5 + 3 + 4 + 4 = 16
....
Quadruplet having sum 13 is closest to the target.Input: arr[] = {1, 2, 3, 4, 10}, target = 20
Output: {1, 3, 5, 10}
Explanation:
Sum of quadruplets:
1 + 2 + 3 + 4 = 10
1 + 2 + 3 + 10 = 16
2 + 3 + 4 + 10 = 19
1 + 3 + 4 + 10 = 18
...
Quadruplet having sum 19 is closest to the target.
Table of Content
The idea is to generate all possible quadruplets using four nested loops and keep track of the smallest difference between target and the sum of each quadruplet. Then, return the quadruplet with the minimum difference between its sum and target.
4 5 3 1
Initially, we sort the input array so that we can apply two pointers technique. Then, we fix the first two elements of the quadruplet using two nested loops and inside the second nested loop we use two pointers technique to find the remaining two elements. Set one pointer at the beginning (left) and another at the end (right) of the remaining array. We then find the absolute difference between the sum of all these four elements and target and store the quadruple having minimum absolute difference.
- If sum < target, move left pointer towards right to increase the sum.
- If sum > target, move right pointer towards left to decrease the sum.
- If sum == target, we’ve found the quadruplet with sum = target, therefore this is the quadruplet with closest sum.
1 3 4 5