Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0818339

Browse files
authored
Create Jump.md
1 parent 27d7bd0 commit 0818339

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

‎Machine Coding/Greedy/Jump.md

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
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.
2+
3+
Return true if you can reach the last index, or false otherwise.
4+
5+
6+
7+
Example 1:
8+
> Input: nums = [2,3,1,1,4]
9+
> Output: true
10+
> Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
11+
12+
```js
13+
function canJump(nums) {
14+
let maxReachable = 0; // The maximum index we can reach so far
15+
16+
for (let i = 0; i < nums.length; i++) {
17+
// If the current index is beyond the max reachable index, we cannot proceed
18+
if (i > maxReachable) {
19+
return false;
20+
}
21+
// Update the max reachable index
22+
maxReachable = Math.max(maxReachable, i + nums[i]);
23+
// If the max reachable index reaches or exceeds the last index, we can reach it
24+
if (maxReachable >= nums.length - 1) {
25+
return true;
26+
}
27+
}
28+
29+
return false;
30+
}
31+
```
32+
#### Example:
33+
Input: nums = [2, 3, 1, 1, 4]
34+
35+
1. maxReachable = 0
36+
2. Iterating through nums:
37+
* At index 0, nums[0] = 2, so maxReachable = Math.max(0, 0 + 2) = 2.
38+
* At index 1, nums[1] = 3, so maxReachable = Math.max(2, 1 + 3) = 4.
39+
* Since maxReachable >= nums.length - 1 is true at this point, we can return true.
40+
Output: true
41+
42+
#### Complexity:
43+
* Time complexity: O(n) where n is the size of the array, as we traverse the array once.
44+
* Space complexity: O(1) because we only use a single variable to store the maximum reachable index.
45+
46+
```js
47+
console.log(canJump([2, 3, 1, 1, 4])); // true
48+
console.log(canJump([3, 2, 1, 0, 4])); // false
49+
console.log(canJump([0])); // true
50+
console.log(canJump([2, 0, 0])); // true
51+
```

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /