The principle looks OK to me.

The only pitfall I see is that you are assuming the input is in the correct order. If you are willing to assume this then fine, if there's a chance it won't be, you'll need another method.