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