O(n) Solution with comments and easy to understand


#1
int getAbs(int a){
    if(a < 0)  {
        return (-1)*a;
    }
    return a;
}
void performCalc(int &a, int &b, int num){
    if(a < b){
            a += num;
        }else if(a > b){
            a -= num;
        }
}
int Solution::coverPoints(vector<int> &a, vector<int> &b) {
    
    int ans = 0;
    for(int i=0;i<a.size()-1;i++){
        
        //First Preference is given to diagonal since its shortest distance
        int diagonal = min(getAbs(a[i]-a[i+1]),getAbs(b[i]-b[i+1]));
        ans += diagonal;
        
        //Updating x coordinate of source point so that we can calculate
        //how far is it from destination vertically
        performCalc(a[i], a[i+1], diagonal);
        
        //Updating y coordinate of source point so that we can calculate
        //how far is it from destination horizontally
        performCalc(b[i], b[i+1], diagonal);
        
        //Till this stage either x or y coordinate of source will be same as x or y 
        //coordinate of destination since we moved source diagonally
        int dist = max(getAbs(a[i]-a[i+1]),getAbs(b[i]-b[i+1]));
        ans += dist;
    }
    return ans;
}