Problem:
You are given an integer array nums
where each element represents the maximum number of indices you can jump forward from that position. Initially, you start at the first index of the array.
Your goal is to determine whether you can reach the last index by jumping through the array based on the values at each position.
Input:
- An array
nums[]
of integers.nums[i]
represents the maximum number of positions you can jump forward from indexi
.
Output:
- Return
true
if it is possible to reach the last index from the first index; otherwise, returnfalse
.
Example 1:
Input:
nums = [2, 3, 1, 1, 4]
Output:
true
Explanation:
- Jump 1 step from index 0 to index 1.
- Then, jump 3 steps from index 1 to reach the last index (index 4).
Example 2:
Input:
nums = [3, 2, 1, 0, 4]
Output:
false
Explanation:
- You will always land on index 3.
- Since the value at index 3 is 0, you cannot jump any further, and it is impossible to reach the last index.
Constraints:
1 <= nums.length <= 10^4
0 <= nums[i] <= 10^5
Solution:
#include <stdbool.h>
#include <stdio.h>
// Function to return the maximum of two numbers
int max(int a, int b)
{
return (a > b) ? a : b;
}
// Function to check if it's possible to reach the last index
bool canJump(int* nums, int numsSize) {
int lastIndex = numsSize - 1;
int reachable = 0;
for (int i = 0; i < numsSize; i++) {
// If the current index is not reachable, return false
if (i > reachable) {
return false;
}
// If we can reach the last index or beyond, return true
if (i + nums[i] >= lastIndex) {
return true;
}
// Update the maximum reachable index
reachable = max(reachable, i + nums[i]);
}
return false;
}
// Main function to test the canJump function
int main() {
int nums[] = {2, 3, 1, 1, 4}; // Test input
int numsSize = sizeof(nums) / sizeof(nums[0]); // Size of the array
// Output whether it's possible to reach the last index
if (canJump(nums, numsSize)) {
printf("Truen");
} else {
printf("Falsen");
}
return 0;
}
Explanation of Code:
-
Function
max
: This function simply returns the maximum of two numbers. It’s used to keep track of the farthest index that can be reached at any point. -
Function
canJump
:reachable
: Keeps track of the farthest index that can be reached so far.lastIndex
: The index of the last element in the array.- The loop iterates through the array, and for each element, it checks if that index is reachable. If the current index is beyond the
reachable
index, it means it’s impossible to proceed, so we returnfalse
. If the current index plus the jump length allows reaching thelastIndex
, we returntrue
.
-
Main function: It initializes an example array, calculates its size, and checks if it is possible to reach the last index.