You need to start debugging the code (which is pretty small IMO). As a starting point, what's the smallest sample with which you can reproduce this problem? What happens when you run this with inputs [5, 4]?
Which IDE are you using to write code? Can you try out the "debug" functionality of that IDE to step through your code and check the values at every step? If not using an IDE, can you try inserting some println statements to dump the arraylist values after each step?