Not able to write the code for the question

I kind of figured out the logic but i am not sure, so please help me out with the approach and if u can share a code it will be helpful.

hi @ayushkotwar2002_78a27ac2b05189a5,
refer