I am getting tle error in last test case
Try to optimise this solution.Your solution is O(N*N) as your finding max element for each āiā.
But You can solve this in O(N) time as numbers are permutation of N,so you know best position for each number.
Use the fact that numbers are from 1 to N and try to make a O(N) solution.