Fastest algorithm to hop through an array

后端 未结 10 1112
栀梦
栀梦 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:22

    Dynamic programming solution:

    keep track for each element the smallest number of steps you can get there and from where you came. then just simply walk through the array and for each element update the available next positions (from i+1 till i+a[i]).

    { 2 , 4 , 1 , 2 , 3 , 2 , 4 , 2} 
      0
    
    { 2 , 4 , 1 , 2 , 3 , 2 , 4 , 2} 
      0   1   1 (num of steps)
          0   0 (source)
      ^         (current position)
    { 2 , 4 , 1 , 2 , 3 , 2 , 4 , 2} 
      0   1   1   2   2   2
          0   0   1   1   1
          ^
    { 2 , 4 , 1 , 2 , 3 , 2 , 4 , 2} 
      0   1   1   2   2   2
              ^
    etc...
    

    This is O(n+sum(a[i])) .. or a bit less, you don't have to go beyond the boundary of the array.

提交回复
热议问题