Here is the code to this problem.
Why am I getting TLE?
You can use faster I/O. scanf can be used in this problem.