Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Problem :-
- ----------
- Given two arrays A and B for length l1 and l2 respectively, and a target value k.
- 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.
- Test Case 1:
- Input: A = [6, 7, 5, 4], B = [1, 1, 8, 2], k = 10
- Output: [7, 2]
- Test Case 2:
- Input: A = [12, 3, 65, 45, 7, 5], B = [45, 67, 8, 4, 65, 37], k = 55
- Output: [45, 8] or [12, 45]
- */
- #include <stdio.h>
- #include <stdlib.h>
- int main(){
- int n=4, a[]={6, 7, 5, 4}, b[]={1, 1, 8, 2}, k=10;
- // int n=6, a[]={12, 3, 65, 45, 7, 5}, b[]={45, 67, 8, 4, 65, 37}, k=55;
- int min=a[0], res[2];
- for(int i=0; i<n; i++){
- for(int j=0; j<n; j++){
- if(abs((a[i]+b[j])-k)<min){
- res[0] = a[i];
- res[1] = b[j];
- min = abs((a[i]+b[j])-k);
- }
- }
- }
- for(int i=0; i<2; i++){printf("%d ", res[i]);}
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment