This is one of those things you could do in a number of ways. Have you looked at the counter object [in particular, its inputs and outputs]? accum?
Here's one of those places we always talk about where it's best to assume that there isn't necessarily a single way to do things, that the possible multiple solutions will reflect the idiosyncracies of their designers, and that the process of putting one's intellect to work trying to construct a solution will, in the long terms, be of greater benefit than solving the problem itself short term.
Your mileage may vary, but it shouldn't. Spend a little time with the manual pages for the counter and accum objects, and with Max Tutorials 31 (counter) and 21 (accum).