Alternative approach | why does it not work?


#1

Given the solution approach, the problem is easy to solve.
However, what I do not understand why the approach below does not solve the problem as well?
The key idea is to iterate over all elements in A and update the indices for B and C if they reduce the minimum difference.

Also I do not clearly see why the provided solution is proven that it always returns a valid solution. Maybe someone could explain?

size_t bA, bB, bC; 
bA = bB = bC = 0; 
int bestVal = numeric_limits<int>::max();

int cB, cC; 
cB = cC = 0; 

for(size_t i = 0; i < A.size(); i++)
{
    auto cA = A[i];
    //cout << "cA: " << cA << endl;
    while(cB < B.size()-1 && abs(cA-B[cB+1]) < abs(cA-B[cB]))
    {
        cB++;
        //cout << "update cB to: " << B[cB] << endl;
    }
    
    while(cC < C.size()-1 && min(abs(cA-C[cC+1]), abs(B[cB]-C[cC+1])) < min(abs(cA-C[cC]), abs(B[cB]-C[cC])))
    {
        cC++;
        //cout << "update cC to: " << C[cC] << endl;
    }
    
    auto cDiff = diff(A, B, C, i, cB, cC);
    //cout << "cDiff: " << cDiff << endl;
    if(cDiff < bestVal)
    {
        bestVal = cDiff;
        //cout << "update bestVal to: " << bestVal << endl;
    }
    //cB = max(0, cB-1);
    //cC = max(0, cC-1);
    //cB = 0; 
    //cC = 0; 
}
return bestVal;