-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Time: 991 ms (68.86%) | Memory: 22.4 MB (80.25%) - LeetSync
- Loading branch information
1 parent
cd3e9b0
commit 6dfc3d9
Showing
1 changed file
with
18 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
class Solution: | ||
def cherryPickup(self, grid: List[List[int]]) -> int: | ||
m, n = len(grid), len(grid[0]) | ||
dp = [[[-1] * n for _ in range(n)] for _ in range(m)] | ||
dp[0][0][n-1] = grid[0][0] + grid[0][n-1] | ||
|
||
for i in range(1, m): | ||
for j in range(n): | ||
for k in range(j+1, n): | ||
for x in range(-1, 2): | ||
for y in range(-1, 2): | ||
if 0 <= j+x < n and 0 <= k+y < n: | ||
prev = dp[i-1][j+x][k+y] | ||
if prev != -1: | ||
dp[i][j][k] = max(dp[i][j][k], prev + grid[i][j] + (grid[i][k] if j != k else 0)) | ||
|
||
ans = max(max(row) for row in dp[m-1]) | ||
return ans if ans != -1 else 0 |