#1463

Cherry Pickup II

Hard
ArrayDynamic ProgrammingMatrixDynamic ProgrammingMatrix Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(3^(rows))
O(rows * cols^2)
Space
O(1)
O(rows * cols^2)
💡

Intuition

Time O(rows * cols^2)Space O(rows * cols^2)

The optimal solution uses dynamic programming to store results of subproblems, allowing us to avoid redundant calculations. By defining a 3D DP array, we can efficiently compute the maximum cherries collected by both robots.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a DP array where dp[i][j][k] represents the maximum cherries collected when Robot 1 is at column j and Robot 2 is at column k on row i.
  2. 2Step 2: Iterate through each row and update the DP array based on possible movements of both robots.
  3. 3Step 3: Return the maximum cherries collected from the last row.
solution.py16 lines
1def cherryPickup(grid):
2    rows, cols = len(grid), len(grid[0])
3    dp = [[[-1] * cols for _ in range(cols)] for _ in range(rows)]
4    for j in range(cols):
5        for k in range(cols):
6            dp[0][j][k] = grid[0][j] + (grid[0][k] if j != k else 0)
7    for i in range(1, rows):
8        for j in range(cols):
9            for k in range(cols):
10                max_cherries = 0
11                for new_j in [j-1, j, j+1]:
12                    for new_k in [k-1, k, k+1]:
13                        if 0 <= new_j < cols and 0 <= new_k < cols:
14                            max_cherries = max(max_cherries, dp[i-1][new_j][new_k])
15                dp[i][j][k] = grid[i][j] + (grid[i][k] if j != k else 0) + max_cherries
16    return max(dp[rows-1][j][k] for j in range(cols) for k in range(cols))

Complexity note: The time complexity is polynomial because we iterate through each row and each possible combination of robot positions, leading to a manageable number of calculations.

  • 1Both robots can collect cherries independently, but they must avoid double counting when they land on the same cell.
  • 2Dynamic programming helps break down the problem into manageable subproblems, allowing for efficient computation.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.