Showing TLE...Passing one test case

Here i have written this code


It is showing tle for two cases…
Do i have to implement it using D.P…
Or what changes should i do in my code…
I think my logic is correct