1
- def greedy (k ,a ):
2
-
3
- def do_stuff (x ,y ,i ,j ,l ):
4
- if a [j ]== x : #check previous obstacle and change lane
5
- return y
6
- elif a [j ]== y :
7
- return x
8
- else :
9
- while i < n and (a [i + 1 ]== 0 or a [i + 1 ]== l ):#to avoid 0s and same lane duplicates
10
- i += 1
11
- if i == n :
12
- return - 1
13
- if a [i + 1 ]== x : #check the next coming obstacle
14
- return y
15
- elif a [i + 1 ]== y :
16
- return x
17
- n = k - 1
18
- ans = 0
19
-
20
- l = 2 #current lane
21
-
22
- i = 0
23
- while i < n :
24
- if l == a [i + 1 ]: #when we encounter next obstacle
25
- j = i #stored for checking before obstacle
26
- while i < n and l == a [i + 1 ]: #avoiding same lane duplicates
27
- i += 1
28
- ans += 1
29
- if i == n :
30
- break
31
-
32
- if l == 2 : #deciding which lane to shift next
33
- l = do_stuff (1 ,3 ,i ,j ,l )
34
- elif l == 1 :
35
- l = do_stuff (2 ,3 ,i ,j ,l )
36
- else :
37
- l = do_stuff (1 ,2 ,i ,j ,l )
38
-
39
- if l == - 1 : #case when i==n hits
40
- break
41
-
42
- if i > 0 : #edge case
43
- i -= 1
44
- i += 1
45
- return ans
46
-
47
1
class Solution :
48
2
def minSideJumps (self , obstacles : List [int ]) -> int :
49
- return greedy (len (obstacles ),obstacles )
3
+
4
+ """
5
+ # TLE Recursion DP
6
+ @cache
7
+ def dp(curr_lane = 2, point = 0):
8
+ if point == len(obstacles)-1:
9
+ return 0
10
+ if obstacles[point+1] == curr_lane:
11
+ return min(dp(lane, point+1) for lane in range(1, 4) if obstacles[point+1] != lane and obstacles[point]!=lane) + 1
12
+
13
+ return dp(curr_lane, point+1)
14
+
15
+
16
+ return dp()
17
+
18
+ """
19
+
20
+ n = len (obstacles )
21
+ dp = [[0 , 0 , 0 , 0 ] for _ in range (n )]
22
+
23
+ for point in range (n - 2 , - 1 , - 1 ):
24
+ for curr_lane in range (4 ):
25
+ if obstacles [point + 1 ] == curr_lane :
26
+ dp [point ][curr_lane ] = min (dp [point + 1 ][lane ] for lane in range (1 , 4 ) if obstacles [point + 1 ] != lane and obstacles [point ]!= lane ) + 1
27
+ else :
28
+ dp [point ][curr_lane ] = dp [point + 1 ][curr_lane ]
29
+
30
+ return dp [0 ][2 ]
0 commit comments