Prateek loves candy problem

time limit is exceeded what should be my logic by naive approach time complexity that is approaching is of the order of 10**12…what should be my approach