Advertisement
DeepRest

Cherry Pickup II

Jan 8th, 2022 (edited)
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.33 KB | None | 0 0
  1. #Bottom up Approach Space optimised
  2. '''
  3. Both robots move down at same time (thus, at same row always)
  4. Dp[i][j][k] = max cherries picked up with the initial position of two robots being (i, j) and (i, k)
  5. Dp[i][j][k] = grid[j] + grid[k] + max(dp[i+1][a][b]) If j != k
  6.            = grid[j] + max(dp[i+1][a][b]) ... J == k
  7.            = 0 for i>=rows, j,k<0 j,k >= cols
  8. Here |j-a| <= 1 and |k-b| <= 1
  9. Time: O(m*n*n)
  10. Space: O(n*n)
  11. '''
  12. class Solution:
  13.     def cherryPickup(self, grid: List[List[int]]) -> int:
  14.         rows = len(grid)
  15.         cols = len(grid[0])
  16.         dp = [[0]*cols for _ in range(cols)]
  17.         for i in range(rows-1, -1, -1):
  18.             temp = [ele[:] for ele in dp]
  19.             for j in range(cols):
  20.                 for k in range(j, cols):
  21.                     m = 0
  22.                     for a in range(-1, 2):
  23.                         for b in range(-1, 2):
  24.                             c1 = j + a
  25.                             c2 = k + b
  26.                             if 0<=c1<cols and 0<=c2<cols:
  27.                                 m = max(m, dp[c1][c2])
  28.                     if j == k:
  29.                         temp[j][k] = temp[k][j] = grid[i][j] + m
  30.                     else:
  31.                         temp[j][k] = temp[k][j] = grid[i][j] + grid[i][k] + m          
  32.             dp = temp
  33.         return dp[0][cols-1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement