Problem 1406

Abstract / Summary

Two players take turns picking stones from piles to maximize their score and the goal is to determine if the first player can win given optimal play.

Note

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

Python 1406.py

class Solution:
    def stoneGameIII(self, stoneValue: List[int]) -> str:
        @cache
        def deeper(pos):
            if pos >= len(stoneValue):
                return 0

            take = stoneValue[pos]
            best = take - deeper(pos + 1)

            for i in range(pos + 1, pos + 2+1):
                if i < len(stoneValue):
                    take += stoneValue[i]
                    best  = max(best, take - deeper(i + 1))

            return best

        result = deeper(0)
        if result == 0:
            return "Tie"
        return "Alice" if result > 0 else "Bob"
21 lines | 618 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 63% (100k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Dynamic Programming
  • Game Theory
  • Math
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 “Stone Game III” problem using a recursive depth-first search with memoization. The core idea is to compute, for each starting position in the array, the maximum net score a player can achieve assuming optimal play from both sides. The recursion returns the difference between the current player’s total and the opponent’s total from that position onward. The final sign of this difference determines whether Alice wins, Bob wins, or the game ends in a tie.

Key Steps

The algorithm begins by defining a cached helper function deeper. The base case checks whether the current index has moved beyond the end of the stoneValue list; in that situation the net contribution is zero because no stones remain to be taken.

@cache
def deeper(pos):
    if pos >= len(stoneValue):
        return 0

The first move considered is taking a single stone at the current position. The value of that stone is stored in take, and the provisional best net score is computed as the value taken minus the opponent’s optimal response from the next position.

    take = stoneValue[pos]
    best = take - deeper(pos + 1)

A loop then explores the two-stone and three-stone take options. For each additional stone that stays within bounds, the cumulative take is updated, and the algorithm evaluates the net score if the player stops after that many stones. The max operation ensures that the best achievable net difference is retained.

    for i in range(pos + 1, pos + 2+1):
        if i < len(stoneValue):
            take += stoneValue[i]
            best  = max(best, take - deeper(i + 1))

After all legal moves from the current position have been examined, the helper returns the optimal net score for that position.

    return best

The top-level call deeper(0) yields the net advantage for the player who starts the game (Alice). The final conditional translates the numeric result into the required string output.

result = deeper(0)
if result == 0:
    return "Tie"
return "Alice" if result > 0 else "Bob"

Edge Cases

When the input list is empty, the base case of deeper is triggered immediately, returning zero. Consequently the outer logic classifies the outcome as a tie, which correctly reflects that no player can obtain any points.

If the list contains fewer than three elements, the loop that attempts to take up to three stones gracefully handles the situation because the if i < len(stoneValue) guard prevents out-of-range access. For a single-element list, only the first take assignment is used; for a two-element list, the loop executes once, adding the second stone and evaluating the two-stone take. The algorithm never attempts to read beyond the array bounds.

Negative stone values are also accommodated. Since the recursion works with the raw sum of taken stones, a negative take can reduce the net score, and the max comparison still selects the move that yields the highest net advantage, even if that advantage is negative. This behavior correctly models scenarios where all remaining stones have negative values, forcing a player to minimize loss.

When the cumulative sum of stones from a certain position onward is zero, the recursion may encounter multiple paths that lead to the same net result. The memoization ensures that each position is evaluated only once, so repeated identical subproblems do not cause redundant computation.

Performance Optimizations

The most significant optimization is the use of the @cache decorator on the recursive helper. By storing the result of deeper(pos) for each distinct pos, the algorithm eliminates exponential recomputation of overlapping subproblems. Each array index is processed a single time, and subsequent calls retrieve the pre-computed value in constant time.

The loop that iterates over possible take lengths is bounded to at most two additional iterations (for taking two or three stones). This tight bound keeps the per-call work minimal while still covering all legal moves defined by the game rules.

The implementation avoids constructing auxiliary data structures such as prefix sums or explicit DP tables. By directly using the recursion and caching, the code maintains a compact memory footprint, storing only the cached results for each index and a few scalar variables per call.

The final decision logic (if result == 0, return "Alice" if result > 0 else "Bob") performs a single comparison to map the numeric outcome to the required string, avoiding any unnecessary branching or additional calculations.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a long row of yummy candies laid out on a table. Two players take turns picking up candies from the front of the line. Each player can decide to grab one, two, or three candies at once. The goal is to collect more candy than the other person.

The code works like a very smart thinking machine that looks at all the possible moves. It imagines every choice someone could make and then thinks about what the next person would do in response. It keeps doing this over and over until there are no candies left, like planning out a perfect move in a game of checkers.

The part called deeper is the smart machine looking ahead. It starts at the very first candy and asks what happens if it takes one, two, or three. It then subtracts what the next person would get from what it gathers itself to see the difference in points. By doing this for the whole row, the computer compares the scores at the end. After checking every single way the game could go, the code compares the final totals. If the number is bigger than zero, the person who went first is the winner. If the number is smaller, the second person wins. If the numbers match perfectly, it ends in a tie.

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 = 7 | μ = 7.11 | σ = 1.40

Complexity Analysis

Time: linear
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++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go Rust TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
FelixFan1122 Java
fsq C++
gouthampradhan Java
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
MacJim C++
muhammadfarhankt Go
varunu28 Java
wisdompeak C++
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
FelixFan1122 Java
fsq C++
gouthampradhan Java
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
MacJim C++
muhammadfarhankt Go
varunu28 Java
wisdompeak C++
withaarzoo C++
30 links | 18 authors | 7 languages

Videos

8 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