The Jump Game problem is a classic algorithmic challenge where you determine if you can reach the last index of an array starting from the first index. Each element in the array represents the maximum jump length you can take from that position.
Problem Statement
Given an array of non-negative integers, where each integer represents the maximum jump length at that position, return true if you can reach the last index, and false otherwise.
C# Implementation
Here’s a C# implementation using a greedy approach:
public class Solution {
public bool CanJump(int[] nums) {
int maxReach = 0;
int n = nums.Length;
for (int i = 0; i < n; i++) {
// If the current index is greater than the maximum reachable index,
// we cannot move further, hence return false.
if (i > maxReach) {
return false;
}
// Update the maximum reachable index
maxReach = Math.Max(maxReach, i + nums[i]);
// If we can reach the last index, return true
if (maxReach >= n - 1) {
return true;
}
}
return false;
}
}
Explanation
-
Initialization:
- We start by initializing a variable
maxReach, which keeps track of the farthest index we can reach at any point in the array.
- We start by initializing a variable
-
Iterating Through the Array:
- We loop through each index
iin the array:- If
iexceedsmaxReach, it means we cannot reach this index from any previous index, so we returnfalse. - We update
maxReachby comparing its current value withi + nums[i], which represents how far we can reach from the current index. - If at any point
maxReachis greater than or equal to the last index (n - 1), we returntrue, indicating we can reach the end.
- If
- We loop through each index
-
Return Value:
- If we finish the loop without returning, it means we cannot reach the last index, and we return
false.
- If we finish the loop without returning, it means we cannot reach the last index, and we return
Example Walkthrough
Consider the array [2, 3, 1, 1, 4].
-
Initialization:
maxReach = 0,n = 5.
-
Iteration:
- For
i = 0:maxReach = max(0, 0 + 2) = 2. - For
i = 1:maxReach = max(2, 1 + 3) = 4. - For
i = 2:maxReach = max(4, 2 + 1) = 4. - For
i = 3:maxReach = max(4, 3 + 1) = 4. - For
i = 4: SincemaxReachis already4, which is greater than4, we don’t check further.
- For
Since maxReach reaches the last index, the function returns true.
Complexity
- Time Complexity: O(n), where n is the number of elements in the array, as we traverse the array once.
- Space Complexity: O(1), as we only use a constant amount of space for variables.
This greedy approach is efficient and straightforward for solving the Jump Game problem!