#741

Cherry Pickup

Hard
ArrayDynamic ProgrammingMatrixDynamic ProgrammingBacktrackingGrid Traversal
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n²)
💡

Intuition

Time O(n²)Space O(n²)

The optimal solution uses dynamic programming to store the maximum cherries collected at each cell during the forward and backward traversal. This avoids redundant calculations and significantly reduces the time complexity.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP table to store the maximum cherries collected at each cell during the forward traversal.
  2. 2Step 2: Fill the DP table by iterating through the grid, updating the maximum cherries possible at each cell.
  3. 3Step 3: After reaching the destination, reset the grid and repeat the process for the backward traversal, updating the DP table again.
solution.py16 lines
1# Full working Python code
2class Solution:
3    def cherryPickup(self, grid):
4        n = len(grid)
5        dp = [[0] * n for _ in range(n)]
6        for i in range(n):
7            for j in range(n):
8                if grid[i][j] == -1:
9                    dp[i][j] = -1
10                else:
11                    if i > 0:
12                        dp[i][j] = max(dp[i][j], dp[i-1][j])
13                    if j > 0:
14                        dp[i][j] = max(dp[i][j], dp[i][j-1])
15                    dp[i][j] += grid[i][j]
16        return max(0, dp[n-1][n-1])

Complexity note: The time complexity remains O(n²) due to the nested loops filling the DP table, but we now use additional space to store results, leading to O(n²) space complexity.

  • 1Dynamic programming can significantly optimize recursive solutions by storing intermediate results.
  • 2Understanding the grid boundaries and thorn placements is crucial for pathfinding.

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