Topic Link: Jump Game
Given an array of non-negative integers, you is initially positioned at the first index of the array.
Each element of the array represents your maximum jump length is at that position.
Determine if you is able to reach the last index.
For example:
The requirement of this problem is given an array of integers, and the array elements represent the maximum distance each can jump. Then the initial position in the first element of the array returns whether the number reaches the last element.
Using the idea of greed, using reach variable maintenance can reach the furthest distance, that is, the global optimal solution. When traversing to I, the local optimal solution is a[i]+i, so the global optimal solution at this time is the maximum of reach and a[i]+i: Reach = Max (reach, A[i] + i).
And the Jump Game II problem, which is the ascent of this question, requires calculating the minimum number of steps to reach the last element.
Time complexity: O (N)
Space complexity: O (1)
1 class Solution2 {3 Public:4 BOOL Canjump(int A[], int N)5 {6 int reach = 0;7 for(int I = 0; I <= reach && I < N; ++ I)8 reach = Max(reach, A[I] + I);9 Ten return reach >= N - 1; One } A };
Reprint please indicate source: Leetcode---55. Jump Game
Leetcode---55. Jump Game