class Solution {
//get the max reachable nextPos at every step O(n)
public:
int jump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(0 == n) return 0;
int nowPos = 0;
int nextPos = 0;
int ans = 0;
while (true)
{
if(nextPos >= n-1)
break;
int maxPos = -1;
for (int i = nowPos; i <= nextPos; ++i)
maxPos = max(i+A[i], maxPos);
nowPos = nextPos;
nextPos = maxPos;
ans++;
}
return ans;
}
};
second time
class Solution {
public:
int jump(int A[], int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int k = 0;
int start = 0;
int end = 0;
while(end < n-1)
{
int newEnd = INT_MIN;
for(int i = start; i <= end; ++i)
newEnd = max(newEnd, A[i]+i);
if(newEnd == end) return -1;
start = end+1;
end = newEnd;
++k;
}
return k;
}
};