Code is giving TLE

Can you check if the code is correct and how can I optimize it? Can’t figure out how to optimize this.