Skip to content

Commit 01608e1

Browse files
authored
Create Minimum Jumps (#882)
2 parents 94e32b9 + ffb5d76 commit 01608e1

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Minimum Jumps

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
int minJumps(vector<int>& arr) {
4+
int n = arr.size();
5+
if (n <= 1) return 0; // Already at last index
6+
if (arr[0] == 0) return -1; // Can't move anywhere
7+
8+
int maxReach = arr[0]; // Farthest index reachable
9+
int steps = arr[0]; // Steps left in current jump
10+
int jumps = 1; // We make the first jump from index 0
11+
12+
for (int i = 1; i < n; i++) {
13+
if (i == n - 1) return jumps; // Reached last index
14+
15+
maxReach = max(maxReach, i + arr[i]);
16+
steps--;
17+
18+
if (steps == 0) { // Need to make another jump
19+
jumps++;
20+
if (i >= maxReach) return -1; // Can't move further
21+
steps = maxReach - i;
22+
}
23+
}
24+
return -1; // If end is never reached
25+
}
26+
};

0 commit comments

Comments
 (0)