If all pointers are valid
if ( l1 <= r1 && l2 <= r2 ) { if ( K - a [ l1 ] < b [ r2 ] - 1 ) { int sub = min ( b [ r2 ] - 1 , -1 * diff ) ; diff += sub ; b [ r2 ] -= sub ; r2 -- ; } else { int sub = min ( K - a [ l1 ] , -1 * diff ) ; diff += sub ; a [ l1 ] -= sub ; l1 ++ ; } }