Problem 1686

Abstract / Summary

Alice and Bob take turns picking numbers from either end of a list to maximize their score difference in a game with specific rules.

Note

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

Python 1686.py

class Solution:
    def stoneGameVI(self, aliceValues: List[int], bobValues: List[int]) -> int:
        diffs = [ ( a, b ) for a, b in zip(aliceValues, bobValues) ]
        # pick largest values first (either boosts own value or prevents opponent from doing so)
        diffs.sort(reverse = True, key = lambda x : x[0] + x[1])

        result = 0
        player = 0 # alternate between 0 and 1
        for d in diffs:
            sign    = 1 - 2 * player # Alice +1, Bob -1
            result += d[player] * sign
            player ^= 1

        if result == 0:
            return 0
        return +1 if result > 0 else -1
16 lines | 639 bytes | submitted November 21, 2023 | GitHub   23% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 61% (40k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Game Theory
  • Greedy
  • Heap (Priority Queue)
  • Math
  • Sorting
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 two-player stone picking problem by converting the pair of values for each stone into a single sortable metric, then simulating an optimal alternating selection. The algorithm builds a list of paired values, orders the stones so that the most influential ones are considered first, and accumulates a signed score that reflects Alice’s advantage over Bob. The final sign of this accumulated score determines the winner.

Construction of Paired Values

The first logical step creates a list of tuples, each containing Alice’s and Bob’s valuation for the same stone.

diffs = [ ( a, b ) for a, b in zip(aliceValues, bobValues) ]

By using a list comprehension together with zip, the code efficiently pairs corresponding entries without an explicit loop, keeping the operation concise and cache-friendly.

Ordering by Combined Influence

The next phase sorts the list of tuples in descending order based on the sum of the two valuations.

diffs.sort(reverse = True, key = lambda x : x[0] + x[1])

Sorting by a + b ensures that stones with the highest total impact-whether they boost Alice’s score or deny Bob a large gain-are examined first. The reverse=True flag places the most critical stones at the front, allowing the subsequent simulation to process them in optimal order.

Alternating Turn Simulation

A variable result tracks the net advantage, while player toggles between the two participants.

result = 0
player = 0 # alternate between 0 and 1
for d in diffs:
    sign    = 1 - 2 * player # Alice +1, Bob -1
    result += d[player] * sign
    player ^= 1

The expression 1 - 2 * player yields +1 for Alice (when player is 0) and -1 for Bob (when player is 1). Multiplying the current player’s valuation by this sign adds Alice’s gain or subtracts Bob’s gain from the cumulative total. The use of the bitwise XOR operator ^= to flip player between 0 and 1 is a compact and fast way to alternate turns without conditional branching.

Determining the Outcome

After processing all stones, the code evaluates the sign of result.

if result == 0:
    return 0
return +1 if result > 0 else -1

A zero total indicates a perfect balance, leading to a draw (0). A positive total means Alice’s accumulated advantage outweighs Bob’s, so the function returns +1. Conversely, a negative total yields -1, indicating Bob’s superiority.

Edge Cases Handled

When both players receive identical total scores, the result variable becomes exactly zero, and the function correctly returns a draw. The sorting step also gracefully handles stones where both valuations are zero; such entries are placed at the end of the list and have no effect on the final score. Additionally, the algorithm works for input lists of length one, where the single stone’s sum determines the order and the alternating logic still applies correctly.

Performance Optimizations

The code leverages several micro-optimizations. The list comprehension for building diffs avoids the overhead of repeatedly appending to a list inside a loop. Sorting with a simple lambda that computes x[0] + x[1] is inexpensive because it operates on integer addition, which is fast in Python. The turn-alternation uses a bitwise XOR (player ^= 1) instead of an if statement, reducing branch mispredictions. The sign calculation 1 - 2 * player is a constant-time arithmetic expression that eliminates the need for separate conditional branches for each player. Together, these choices keep the runtime tight while preserving readability.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a game where two friends are picking up stones in a pile. Each stone has a number written on it showing how much it is worth to each person. Because some stones are more valuable than others, the friends decide to be very smart about which ones they grab. They add the value for both people together to figure out which stone is the most important one to take next. By doing this, they make sure they get the biggest prizes while keeping the other person from getting them.

The code starts by looking at all the stones and pairing up their values. Then, it sorts them from the biggest ones to the smallest ones based on that total value. Once the stones are lined up in order, the friends start taking turns. When it is the first friend's turn, they add their points to a score. When it is the second friend's turn, they take those points away from the total to show they are winning some. After all the stones are gone, the final score tells everyone who ended up with the most value. If the score is positive, the first friend won. If the score is negative, the second friend won. If the score is zero, it means they both finished with the exact same amount of value.

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.56 | σ = 1.20

Complexity Analysis

Time: loglinear
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
fsq C++
JoshCrozier JS
lkwq007 Python
MacJim C++
suxrobGM C#
wisdompeak C++
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
fsq C++
JoshCrozier JavaScript
lkwq007 Python
MacJim C++
suxrobGM C#
wisdompeak C++
23 links | 13 authors | 7 languages

Videos

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

Similar Problems

8 similar problems

Solved On The Same Day

9 solutions   November 21, 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