File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
3986-maximum-path-score-in-a-grid Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ # time complexity: O(m*n*k)
2+ # space complexity: O(m*n*k)
3+ from typing import List
4+
5+
6+ class Solution :
7+ def maxPathScore (self , grid : List [List [int ]], k : int ) -> int :
8+ ROW , COL = len (grid ), len (grid [0 ])
9+
10+ dp = [[[- 10 ** 9 for _ in range (k + 1 )]
11+ for _ in range (COL )] for _ in range (ROW )]
12+
13+ startVal = grid [0 ][0 ]
14+ startCost = 1 if startVal in (1 , 2 ) else 0
15+ if startCost <= k :
16+ dp [0 ][0 ][startCost ] = startVal
17+
18+ for r in range (ROW ):
19+ for c in range (COL ):
20+ for i in range (k + 1 ):
21+ if dp [r ][c ][i ] < 0 :
22+ continue
23+ if c + 1 < COL :
24+ val = grid [r ][c + 1 ]
25+ newCost = i + (1 if val in (1 , 2 ) else 0 )
26+ if newCost <= k :
27+ dp [r ][c + 1 ][newCost ] = max (dp [r ]
28+ [c + 1 ][newCost ], dp [r ][c ][i ] + val )
29+ if r + 1 < ROW :
30+ val = grid [r + 1 ][c ]
31+ newCost = i + (1 if val in (1 , 2 ) else 0 )
32+ if newCost <= k :
33+ dp [r + 1 ][c ][newCost ] = max (dp [r + 1 ]
34+ [c ][newCost ], dp [r ][c ][i ] + val )
35+
36+ result = - 1
37+ for i in range (k + 1 ):
38+ if dp [ROW - 1 ][COL - 1 ][i ] >= 0 :
39+ result = max (result , dp [ROW - 1 ][COL - 1 ][i ])
40+
41+ return result if result >= 0 else - 1
42+
43+
44+ grid = [[0 , 1 ], [2 , 0 ]]
45+ k = 1
46+ print (Solution ().maxPathScore (grid , k ))
47+ grid = [[0 , 1 ], [1 , 2 ]]
48+ k = 1
49+ print (Solution ().maxPathScore (grid , k ))
You can’t perform that action at this time.
0 commit comments