Problem Link — problem
code —
code
Why is this giving TLE? I am only visiting each array index only once.I am considering this as a graph problem where the neighbors of a node are all the indices reachable from that index.Then BFS will clearly result in the shortest path to reach index n-1.Can someone help me please..
You are visiting each index only once, but for every index you do a loop. If the there are N elements your worstcase in O(N^2), for example if all the values are greater tha N.
Thanks mate . Is there any workaround I can modify BFS solution for this problem or is DP the only approach to solve this problem and BFS is wrong??
You can use the same trick that I used for my solution, but consider that for the nature of the problem you will update the values in the same order as I do, from left to right so I dont think that BFS is a good idea.
My solution is much simpler and works: The distance of the first value is 0, after that you will update the distance of every value once. I iterate over all values keeping the next value that I have not visited yet, when I update the next values I don't iterate over the value for which I have already found the minimum distance.
Instead of running loop inside, you can keep track from where you need to start.