Fastest algorithm to hop through an array

后端 未结 10 1131
栀梦
栀梦 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条回答
  •  猫巷女王i
    2021-02-05 17:16

    Use your basic idea, but start from the beginning instead and you can get O(n).

    The goal is to make a sequence (A_i1, A_i2, ..., A_ik, ...) such that

    1. positions 0,1,2,...,ik can be reached in k or fewer steps

    2. positions i(k-1)+1, i(k-1)+2, ..., ik cannot be reach in fewer than k steps

    The base case is easy:

    i0 = 0
    i1 = A[0]
    

    and the inductive part isn't too complicated:

    i(k+2) = max { A_(ik+1) + ik , A_(ik+1) + ik+1, ..., A_(i(k+1)) + i(k+1) }
    

提交回复
热议问题