Triplet sum closest to given numberProblem Statement: Given an array of integers, consisting of N integers denoted as arr[], and an integer X, the objective is to identify three integers within arr[] such that their sum closely approximates the value of X. Sample Test Cases: Test Case 1: Input: arr[] = {-3, 5, 2, -8, 10}, X = 7 Output: 7 Explanation: Sums of triplets: (-3) + 5 + 2 = 4 5 + 2 + (-8) = -1 (-3) + 2 + (-8) = -9 4 is closest to 7. Test Case 2: Input: arr[] = {0, -6, 4, 9, -2}, X = 3 Output: 1 Explanation: Sums of triplets: 0 + (-6) + 4 = -2 (-6) + 4 + 9 = 7 0 + 4 + (-2) = 2 1 is closest to 3. Test Case 3: Input:arr[] = {7, -1, 3, 6, -4}, X = 2 Output: 0 Explanation: Sums of triplets: 7 + (-1) + 3 = 9 (-1) + 3 + 6 = 8 7 + 3 + (-4) = 6 0 is closest to 2. Method 1: Naive approach A straightforward method involves exhaustively exploring all subsets of size three within the given array. Throughout this process, the algorithm maintains a record of the variance between the target value, X, and the sum of each subset. The subset with the minimum difference between its sum and X is then identified and returned as the result. Algorithm:
If so, update the current minimum. Finally, output the closest sum obtained. Java Implementation of the above mentioned approach Output: Complexity Analysis: Time Complexity: O(n^3)
Space Complexity: O(1)
Method 2: Using Sorting
Utilizing the Two Pointers algorithm results in a linear time complexity, making it a superior alternative to nested loops Algorithm:
Java Implementation of the above mentioned approach Output: Complexity Analysis: Time Complexity: O(n^2) Space Complexity: O(1) |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India