Movatterモバイル変換


[0]ホーム

URL:


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

Commite47ca45

Browse files
committed
Add greedy solution for Jump Game.
1 parentafbdb89 commite47ca45

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
/**
2+
* GREEDY approach of solving Jump Game.
3+
*
4+
*@param {number[]} numbers - array of possible jump length.
5+
*/
6+
exportdefaultfunctiongrdJumpGame(numbers){
7+
// The "good" cell is a cell from which we may jump to the last cell of the numbers array.
8+
9+
// The last cell in numbers array is for sure the "good" one since it is our goal to reach.
10+
letleftGoodPosition=numbers.length-1;
11+
12+
// Go through all numbers from right to left.
13+
for(letnumberIndex=numbers.length-2;numberIndex>=0;numberIndex-=1){
14+
// If we can reach the "good" cell from the current one then for sure the current
15+
// one is also "good". Since after all we'll be able to reach the end of the array
16+
// from it.
17+
constmaxCurrentJumpLength=numberIndex+numbers[numberIndex];
18+
if(maxCurrentJumpLength>=leftGoodPosition){
19+
leftGoodPosition=numberIndex;
20+
}
21+
}
22+
23+
// If the most left "good" position is the zero's one then we may say that it IS
24+
// possible jump to the end of the array from the first cell;
25+
returnleftGoodPosition===0;
26+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp