Fastest algorithm to hop through an array

后端 未结 10 1307
栀梦
栀梦 2021-02-05 16:52

Start with an array A of positive numbers. Start at index 0. From index i, you can move to index i+x for any x <= A[i]. The goal is to find the minimum number of moves needed

10条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-05 17:34

    I'll go against the flow and tell you that your algorithm is "perfect".

    It uses dynamic programming in its cleanest form, and its complexity is not so bad. In this sense, I'd say it is likely to be what was expected from you at the interview.

    If you have a bound on the entries (say A[i] <= C(N)), then its complexity is O(N * max(C(N), N)). For instance, if all the entries are less than K, it is O(N).

    Using Dijkstra's algorithm (or more generally reducing the problem to a shortest path problem) is smart, but I rank it behind the clean DP solution, since graph algorithms are complex (and it could backfire at an interview if you were asked about them).

    Note that Dijkstra would be O(N C(N) + N log N) instead (N vertices, and N C(N) edges). So depending on C, you are either strictly better or equal in complexity.

提交回复
热议问题