Jump Game — LeetCode #55
3 min readDec 26, 2022
You are given an integer array nums
. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.
Return true
if you can reach the last index, or false
otherwise.
Example 1:
Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Example 2:
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.
Constraints:
1 <= nums.length <= 104
0 <= nums[i] <= 105
Solutions:
Python
class Solution:
def canJump(self, nums: List[int]) -> bool:
n = len(nums)
if n == 0:
return False
if n == 1:
return True
max_reach = 0
for i in range(n):
if i > max_reach:
return False
max_reach = max(max_reach, i + nums[i])
if max_reach >= n - 1:
return True
return False
C#
class Solution {
public bool CanJump(int[] nums) {
int n = nums.Length;
if (n == 0) {
return false;
}
if (n == 1) {
return true;
}
int maxReach = 0;
for (int i = 0; i < n; i++) {
if (i > maxReach) {
return false;
}
maxReach = Math.Max(maxReach, i + nums[i]);
if (maxReach >= n - 1) {
return true;
}
}
return false;
}
}
Java
class Solution {
public boolean canJump(int[] nums) {
int n = nums.length;
if (n == 0) {
return false;
}
if (n == 1) {
return true;
}
int maxReach = 0;
for (int i = 0; i < n; i++) {
if (i > maxReach) {
return false;
}
maxReach = Math.max(maxReach, i + nums[i]);
if (maxReach >= n - 1) {
return true;
}
}
return false;
}
}
Javascript
/**
* @param {number[]} nums
* @return {boolean}
*/
var canJump = function(nums) {
const n = nums.length;
if (n === 0) {
return false;
}
if (n === 1) {
return true;
}
let maxReach = 0;
for (let i = 0; i < n; i++) {
if (i > maxReach) {
return false;
}
maxReach = Math.max(maxReach, i + nums[i]);
if (maxReach >= n - 1) {
return true;
}
}
return false;
};
Typescript
function canJump(nums: number[]): boolean {
const n = nums.length;
if (n === 0) {
return false;
}
if (n === 1) {
return true;
}
let maxReach = 0;
for (let i = 0; i < n; i++) {
if (i > maxReach) {
return false;
}
maxReach = Math.max(maxReach, i + nums[i]);
if (maxReach >= n - 1) {
return true;
}
}
return false;
}
PHP
class Solution {
/**
* @param Integer[] $nums
* @return Boolean
*/
function canJump($nums) {
$n = count($nums);
if ($n == 0) {
return false;
}
if ($n == 1) {
return true;
}
$maxReach = 0;
for ($i = 0; $i < $n; $i++) {
if ($i > $maxReach) {
return false;
}
$maxReach = max($maxReach, $i + $nums[$i]);
if ($maxReach >= $n - 1) {
return true;
}
}
return false;
}
}
I hope this helps! Let me know if you have any questions. Don’t forget to FOLLOW and give some CLAPS to support my content