[InterviewBit] Minimize the absolute difference

Minimize the absolute difference

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int Solution::solve(vector<int> &A, vector<int> &B, vector<int> &C) {
int i = 0, j = 0, k = 0, res = INT_MAX;
int sa = A.size(), sb = B.size(), sc = C.size();
while(i < A.size() or j < B.size() or k < C.size()) {
int a = A[min(i,sa-1)], b = B[min(j,sb-1)], c = C[min(k,sc-1)];
int ma = max({a,b,c}), mi = min({a,b,c});
res = min(res, abs(ma - mi));
if(i < sa and a == mi) i += 1;
else if(j < sb and b == mi) j += 1;
else if(k < sc and c == mi) k += 1;
else break;
}
return res;
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/24/PS/interviewbit/minimize-the-absolute-difference/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.