Skip to content

Commit 5b7d053

Browse files
committed
Add solution #403
1 parent b02baf2 commit 5b7d053

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,7 @@
321321
400|[Nth Digit](./0400-nth-digit.js)|Medium|
322322
401|[Binary Watch](./0401-binary-watch.js)|Easy|
323323
402|[Remove K Digits](./0402-remove-k-digits.js)|Medium|
324+
403|[Frog Jump](./0403-frog-jump.js)|Hard|
324325
404|[Sum of Left Leaves](./0404-sum-of-left-leaves.js)|Easy|
325326
405|[Convert a Number to Hexadecimal](./0405-convert-a-number-to-hexadecimal.js)|Easy|
326327
407|[Trapping Rain Water II](./0407-trapping-rain-water-ii.js)|Hard|

solutions/0403-frog-jump.js

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* 403. Frog Jump
3+
* https://leetcode.com/problems/frog-jump/
4+
* Difficulty: Hard
5+
*
6+
* A frog is crossing a river. The river is divided into some number of units, and at each
7+
* unit, there may or may not exist a stone. The frog can jump on a stone, but it must not
8+
* jump into the water.
9+
*
10+
* Given a list of stones positions (in units) in sorted ascending order, determine if the
11+
* frog can cross the river by landing on the last stone. Initially, the frog is on the
12+
* first stone and assumes the first jump must be 1 unit.
13+
*
14+
* If the frog's last jump was k units, its next jump must be either k - 1, k, or k + 1
15+
* units. The frog can only jump in the forward direction.
16+
*/
17+
18+
/**
19+
* @param {number[]} stones
20+
* @return {boolean}
21+
*/
22+
var canCross = function(stones) {
23+
const dp = new Map();
24+
stones.forEach(stone => dp.set(stone, new Set()));
25+
dp.get(0).add(0);
26+
27+
for (let i = 0; i < stones.length; i++) {
28+
const curr = stones[i];
29+
for (const prevJump of dp.get(curr)) {
30+
for (const jump of [prevJump - 1, prevJump, prevJump + 1]) {
31+
if (jump > 0 && dp.has(curr + jump)) {
32+
dp.get(curr + jump).add(jump);
33+
}
34+
}
35+
}
36+
}
37+
38+
return dp.get(stones[stones.length - 1]).size > 0;
39+
};

0 commit comments

Comments
 (0)