Skip to content

Commit e7d3edc

Browse files
committed
Updated jump game 2
1 parent 78b30b6 commit e7d3edc

File tree

1 file changed

+9
-7
lines changed

1 file changed

+9
-7
lines changed

Hard/JumpGame2.java

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
* The minimum number of jumps to reach the last index is 2. (Jump 1 step from
1414
* index 0 to 1, then 3 steps to the last index.)
1515
*
16-
* Tags: Array, Greedy
16+
* Tags: Array, Greedy, DP
1717
*/
1818
class JumpGame2 {
1919
public static void main(String[] args) {
@@ -22,22 +22,24 @@ public static void main(String[] args) {
2222

2323
/**
2424
* Use last to store how far we already can reach
25+
* Compare i with last
2526
* If we run out of it, update and add 1 more step to result
2627
* Return if last is already bigger than or equal to the length
2728
* Use cur to store how far we can reach for the next step
2829
*/
2930
public int jump(int[] A) {
30-
int res = 0;
31+
int step = 0;
3132
int last = 0; // how far we already can reach
3233
int cur = 0; // how far can we reach for next step
34+
3335
for (int i = 0; i < A.length; i++) {
34-
if (i > last) { // run out of we can reach
36+
if (i > last) { // run out of we can reach, need one more step
3537
last = cur;
36-
res++;
37-
if (last >= A.length) return res;
38+
step++;
39+
if (last >= A.length) return step;
3840
}
3941
cur = Math.max(cur, i + A[i]);
4042
}
41-
return res;
43+
return step;
4244
}
43-
}
45+
}

0 commit comments

Comments
 (0)