Is there other way to solve this problem?

My code is giving time limit exceed for this problem