Code giving TLE

Is this code correct? If yes then how can I optimize it? Can’t figure out how to optimize this.