Skip to content

Commit ec49b85

Browse files
committed
Add solution #818
1 parent 95efabf commit ec49b85

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -626,6 +626,7 @@
626626
815|[Bus Routes](./0815-bus-routes.js)|Hard|
627627
816|[Ambiguous Coordinates](./0816-ambiguous-coordinates.js)|Medium|
628628
817|[Linked List Components](./0817-linked-list-components.js)|Medium|
629+
818|[Race Car](./0818-race-car.js)|Hard|
629630
819|[Most Common Word](./0819-most-common-word.js)|Easy|
630631
821|[Shortest Distance to a Character](./0821-shortest-distance-to-a-character.js)|Easy|
631632
824|[Goat Latin](./0824-goat-latin.js)|Easy|

solutions/0818-race-car.js

+52
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/**
2+
* 818. Race Car
3+
* https://leetcode.com/problems/race-car/
4+
* Difficulty: Hard
5+
*
6+
* Your car starts at position 0 and speed +1 on an infinite number line. Your car can go into
7+
* negative positions. Your car drives automatically according to a sequence of instructions
8+
* 'A' (accelerate) and 'R' (reverse):
9+
* - When you get an instruction 'A', your car does the following:
10+
* - position += speed
11+
* - speed *= 2
12+
* - When you get an instruction 'R', your car does the following:
13+
* - If your speed is positive then speed = -1
14+
* - otherwise speed = 1
15+
*
16+
* Your position stays the same.
17+
*
18+
* For example, after commands "AAR", your car goes to positions 0 --> 1 --> 3 --> 3, and your
19+
* speed goes to 1 --> 2 --> 4 --> -1.
20+
*
21+
* Given a target position target, return the length of the shortest sequence of instructions
22+
* to get there.
23+
*/
24+
25+
/**
26+
* @param {number} target
27+
* @return {number}
28+
*/
29+
var racecar = function(target) {
30+
const dp = new Array(target + 1).fill(Infinity);
31+
dp[0] = 0;
32+
33+
for (let i = 1; i <= target; i++) {
34+
const k = Math.ceil(Math.log2(i + 1));
35+
36+
if ((1 << k) - 1 === i) {
37+
dp[i] = k;
38+
continue;
39+
}
40+
41+
dp[i] = k + 1 + dp[(1 << k) - 1 - i];
42+
43+
for (let j = 0; j < k - 1; j++) {
44+
dp[i] = Math.min(
45+
dp[i],
46+
(k - 1) + 1 + j + 1 + dp[i - ((1 << (k - 1)) - 1) + (1 << j) - 1]
47+
);
48+
}
49+
}
50+
51+
return dp[target];
52+
};

0 commit comments

Comments
 (0)