BackmediumTwo Pointers Oracle TCS

Closest Fair Trade Pair Solution

Problem Statement

You are given two arrays of integers, A and B, and an integer target. Array A is sorted in ascending order, and array B is sorted in descending order. You need to find a pair of elements, one from A and one from B, such that their sum is less than or equal to target. Among all such valid pairs, you must select the one that minimizes the absolute difference between the two chosen elements. If there is a tie in the minimum absolute difference, choose the pair with the maximum sum. If there is still a tie, choose the pair with the larger value from array A. Return the pair as an array [A[i], B[j]]. If no such pair exists, return an empty array.

Example 1
Input
A = [2, 3, 5, 9], B = [10, 8, 4, 1], target = 10
Output
[5, 4]

Explanation: The pairs with sum <= 10 are: (2,8) sum=10 diff=6; (2,4) sum=6 diff=2; (2,1) sum=3 diff=1; (3,4) sum=7 diff=1; (3,1) sum=4 diff=2; (5,4) sum=9 diff=1; (5,1) sum=6 diff=4; (9,1) sum=10 diff=8. The pairs with the minimum absolute difference of 1 are [2, 1], [3, 4], and [5, 4]. Among these, [5, 4] has the maximum sum of 9.

Example 2
Input
A = [1, 2, 3], B = [10, 9, 8], target = 5
Output
[]

Explanation: The smallest possible sum of any pair is A[0] + B[2] = 1 + 8 = 9, which is strictly greater than the target of 5. Thus, no valid pair exists.

Constraints

  • 1 <= A.length, B.length <= 10^5
  • -10^9 <= A[i], B[j], target <= 10^9
  • A is sorted in ascending order.
  • B is sorted in descending order.
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free