Problem 1463

Abstract / Summary

You must find the maximum cherries collected when moving from the start to the end of a grid, moving only down or right each step.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1463.py

class Solution:
    def cherryPickup(self, grid: List[List[int]]) -> int:
        cols = len(grid[0])

        @cache
        def deeper(one, two, row):
            cherries = 0
            if one == two:
                cherries = grid[row][one]
            else:
                cherries = grid[row][one] + grid[row][two]

            if row == len(grid) - 1:
                return cherries

            best = 0
            for a in range(one - 1, one + 2):
                for b in range(two - 1, two + 2):
                    if 0 <= a < cols and 0 <= b < cols and a <= b:
                        best = max(best, deeper(a, b, row + 1))
            return cherries + best

        return deeper(0, cols - 1, 0)
23 lines | 740 bytes | submitted October 3, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 73% (300k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Matrix
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the “Cherry Pickup” problem by modeling the movement of two agents that start at opposite ends of the top row of a rectangular grid. The agents move simultaneously one row down at each step, each choosing to stay in the same column, move left, or move right. The goal is to collect the maximum possible number of cherries, counting a cell only once when both agents occupy it. The solution employs a depth-first search with memoization to explore all feasible paths while avoiding redundant calculations.

Core Logic

Grid dimensions

cols = len(grid[0])

The number of columns is extracted once, allowing the recursive routine to validate column indices efficiently.

Recursive function with caching

@cache
def deeper(one, two, row):
    ...

The inner function deeper receives the current column positions of the two agents (one and two) and the current row index. The @cache decorator automatically stores results for each unique triple (one, two, row). This memoization eliminates exponential recomputation by reusing previously computed sub-problems.

Cherry accumulation for the current row

if one == two:
    cherries = grid[row][one]
else:
    cherries = grid[row][one] + grid[row][two]

When both agents occupy the same cell, the code adds the cell’s value only once; otherwise it sums the values from both distinct cells. This conditional correctly implements the rule that a cherry cannot be double-counted.

Base case - bottom row

if row == len(grid) - 1:
    return cherries

When the agents have reached the last row, the recursion terminates, returning the cherries collected on that final row.

Exploration of next moves

best = 0
for a in range(one - 1, one + 2):
    for b in range(two - 1, two + 2):
        if 0 <= a < cols and 0 <= b < cols and a <= b:
            best = max(best, deeper(a, b, row + 1))
return cherries + best

Two nested loops generate the nine possible combinations of moves for the pair of agents (each can move left, stay, or move right). The conditional 0 <= a < cols and 0 <= b < cols discards moves that would leave the grid boundaries. The additional constraint a <= b removes symmetric states where the agents have simply swapped positions, halving the state space without affecting the optimal result. The variable best tracks the maximum cherries obtainable from any valid continuation, and the function returns the sum of the current row’s cherries and this optimal future value.

Entry point

return deeper(0, cols - 1, 0)

The recursion starts with the leftmost column for the first agent and the rightmost column for the second agent, both positioned on the top row.

Edge Cases Handled

When the grid consists of a single column, both agents start in the same cell; the equality check ensures the cherry is counted only once. The boundary checks inside the nested loops prevent index errors when an agent attempts to move outside the leftmost or rightmost column, which is crucial for grids with only one or two columns. The condition a <= b also gracefully handles the situation where the two agents converge to the same column during the descent, preserving correctness without generating duplicate states.

If the grid has only one row, the base case is triggered immediately after the initial cherry accumulation, returning the correct total without further recursion. The memoization cache automatically handles repeated calls with identical parameters, which can occur when different paths lead to the same pair of positions on a given row.

Performance Optimizations

The primary optimization is the use of the @cache decorator, which stores the result of each distinct state (one, two, row). This transforms the naive exponential exploration into a polynomial-time dynamic programming solution by ensuring each state is computed at most once.

The additional ordering constraint a <= b cuts the number of states roughly in half. Since the two agents are indistinguishable apart from their starting positions, any state where the first agent is to the right of the second is a mirror of a state already considered. By enforcing a non-decreasing order of column indices, the algorithm avoids exploring both mirrored configurations.

Limiting the loops to the range one - 1 to one + 1 (and similarly for two) restricts the branching factor to at most nine valid transitions per state, rather than considering all columns. Combined with the boundary checks, this keeps the recursion tight and prevents unnecessary recursive calls.

The early return on the bottom row eliminates further recursion once the agents have reached the final row, ensuring that the algorithm does not waste cycles on deeper calls that cannot exist.

written by openai gpt

ELI5 - Simplified Explanation

Imagine there is a big square grid full of yummy cherries and two little robots are standing at the top. The first robot starts at the far left and the second robot starts at the far right. They both want to walk all the way down to the bottom of the grid to collect as many cherries as they can along the way.

To make sure they find the best path, the robots think very carefully about every step they take. At each row, they look at the cherries in front of them. If both robots land on the same spot, they share the one cherry there, but if they are on different spots, they each pick up the cherry at their own location. After picking up those cherries, they look ahead to the next row to see which moves will let them pick up even more treats later on.

The robots have a clever trick to help them choose the best path. Whenever they are deciding where to go, they check if they have already tested that specific set of positions before. If they have, they jump straight to the answer they found earlier instead of doing all the hard work again. They keep doing this, moving row by row, checking every diagonal possibility, until they reach the very bottom of the grid. By comparing all these different choices, they figure out exactly which path leads to the biggest pile of cherries.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.37 | σ = 1.28

Complexity Analysis

Time: polynomial
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python Java Go TS
Progiez C++ Python Java
github black-shadows C++
charles-wangkai Java
everthis JS
fpdjsns C++
fsq C++
gouthampradhan Java
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
YuriSpiridonov Python
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fpdjsns C++
fsq C++
gouthampradhan Java
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
suxrobGM C#
trung-hn Python
varunu28 Java
wisdompeak C++
YuriSpiridonov Python
29 links | 19 authors | 7 languages

Videos

7 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

6 easy 4 medium 3 hard
14 solutions   October 3, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality