TLE in CHEFRES

I tried using a different approach to the problem CHEFRES in September Lunchtime. I mapped the intervals onto an array with reference the array’s indices. The interval starts with 1 and ends with 3. The values inside an interval are 0. The values lying outside the interval store the distance to the next interval+3. Can anyone help me understand my mistake and correct the TLE?

Solution link:https://www.codechef.com/viewsolution/20400984

I guess the reason for TLE is the loop,
for j in range(ma,-1,-1), which makes the code run for 10^9 iterations if ‘ma’ is 10^9 , Therefore gives a TLE.

PS: Observe the point the intervals are disjoint.

//