I need help in solving this problem

I need help in solving this problem

Think of it using stacks.
You can store indices in stack.
You can have a detailed explanation