Skip to content

Instantly share code, notes, and snippets.

@junjiah
Created November 18, 2013 09:03
Show Gist options
  • Save junjiah/7524836 to your computer and use it in GitHub Desktop.
Save junjiah/7524836 to your computer and use it in GitHub Desktop.
solved 'Jump Game II' on LeetCode http://oj.leetcode.com/problems/jump-game-ii/
/*
1. first using DP, O(n^2), TLE.
2. then try spliting arrays to intervals by
taking the maximum reach as the boundary.
*/
class Solution {
public:
int jump(int A[], int n) {
if (A[0] == 0 || n == 1) return 0;
int iter = 1, intervalEnd = A[0], res = 1;
while (n-1 > intervalEnd) {
int maxOfInterval = 0;
for (;iter <= intervalEnd;++iter) {
if (A[iter]+iter > maxOfInterval) maxOfInterval = A[iter]+iter;
}
intervalEnd = maxOfInterval;
++res;
}
return res;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment