We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents 94e32b9 + ffb5d76 commit 01608e1Copy full SHA for 01608e1
Minimum Jumps
@@ -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