How to compute a conditional sum of a vector efficiently