Why is my program not passing all test cases?
It is very important to understand whether a program is executing as you wanted it to or not.
It seems to me that you know the logic but the way you have coded it is inappropriate.
I would suggest you to first make a dry run(using pen and paper) on the given test case.
This will help you understand your mistake and the way your program is actually executing.
If you won’t be able to figure it out, feel free to ask.
Hope this would help.