Programmin-in-Python

C Program for the "Closest possible pairs" problem

Jan 28th, 2022
905
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.86 KB | None | 0 0
  1. /*
  2. Problem :-
  3. ----------
  4.  
  5. Given two arrays A and B for length l1 and l2 respectively, and a target value k.
  6. You need to find one value from array A and one from array B such that their sum is closest to the target value k.
  7.  
  8. Test Case 1:
  9. Input: A = [6, 7, 5, 4], B = [1, 1, 8, 2], k = 10
  10. Output: [7, 2]
  11.  
  12. Test Case 2:
  13. Input: A = [12, 3, 65, 45, 7, 5], B = [45, 67, 8, 4, 65, 37], k = 55
  14. Output: [45, 8] or [12, 45]
  15. */
  16.  
  17. #include <stdio.h>
  18. #include <stdlib.h>
  19.  
  20. int main(){
  21.     int n=4, a[]={6, 7, 5, 4}, b[]={1, 1, 8, 2}, k=10;
  22.     // int n=6, a[]={12, 3, 65, 45, 7, 5}, b[]={45, 67, 8, 4, 65, 37}, k=55;
  23.     int min=a[0], res[2];
  24.  
  25.     for(int i=0; i<n; i++){
  26.         for(int j=0; j<n; j++){
  27.             if(abs((a[i]+b[j])-k)<min){
  28.                 res[0] = a[i];
  29.                 res[1] = b[j];
  30.                 min = abs((a[i]+b[j])-k);
  31.  
  32.             }
  33.         }
  34.     }
  35.  
  36.     for(int i=0; i<2; i++){printf("%d ", res[i]);}
  37.     return 0;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment