First of all, use code tags while posting code. The code you posted is very hard to read as its not even formatted.
Secondly, I cant get how are you not getting the logic? Your wrote this code (hopefully), and it runs absolutely fine
Finally my logic for this, a bit simpler