Reputation: 69
QUESTION LINK:
https://www.interviewbit.com/problems/minimize-the-absolute-difference/
It has an ide so you can solve it on the website itself.
QUESTION:
Given three sorted arrays A, B and C of not necessarily same sizes.
Calculate the minimum absolute difference between the maximum and minimum number from the triplet a, b, c such that a, b, c belongs arrays A, B, C respectively. i.e. minimize | max(a,b,c) - min(a,b,c) |.
Example :
Input:
A : [ 1, 4, 5, 8, 10 ]
B : [ 6, 9, 15 ]
C : [ 2, 3, 6, 6 ]
Output:
1
Explanation: We get the minimum difference for a=5, b=6, c=6 as | max(a,b,c) - min(a,b,c) | = |6-5| = 1.
MY SOLUTION:
int Solution::solve(vector<int> &A, vector<int> &B, vector<int> &C) {
int a,b,c,d,e,f,g,i,j;
a=A.pop_back();
b=B.pop_back();
c=C.pop_back();
while(A.size()>0 && B.size()>0 && C.size()>0){
if(a>=b && b>=c){
d = abs(a-c);
if(d<f){
f=d;
}
a=A.pop_back();
}
if(a>=b && c>=b){
d = abs(a-b);
if(d<f){
f=d;
}
a=A.pop_back();
}
if(b>=a && a>=c){
d = abs(b-c);
if(d<f){
f=d;
}
b=B.pop_back();
}
if(b>=a && c>=a){
d = abs(b-a);
if(d<f){
f=d;
}
b=B.pop_back();
}
if(c>=a && a>=b){
d = abs(c-b);
if(d<f){
f=d;
}
c=C.pop_back();
}
if(c>=b && b>=a){
d = abs(c-a);
if(d<f){
f=d;
}
c=C.pop_back();
}
}
cout<<f;
}
Upvotes: 0
Views: 378
Reputation: 119194
The pop_back()
function doesn't return the element popped. You have to do this:
a = A.back();
A.pop_back();
... and so on.
See Why doesn't std::queue::pop return value.? for explanation of the API design.
Upvotes: 2