Alice and Bob take turns playing a game, with Alice starting first.
There are n stones in a pile. On each player's turn, they can remove a stone from the pile and receive points based on the stone's value. Alice and Bob may value the stones differently.
You are given two integer arrays of length n, aliceValues and bobValues. Each aliceValues[i] and bobValues[i] represents how Alice and Bob, respectively, value the i-th stone.
The winner is the person with the most points after all the stones are chosen. If both players have the same amount of points, the game results in a draw. Both players will play optimally. Both players know the other's values.
Determine the result of the game, and:
If Alice wins, return 1.
If Bob wins, return -1.
If the game results in a draw, return 0.
Input & Output
Example 1 — Alice Wins
$Input:aliceValues = [1,3], bobValues = [3,1]
›Output:1
💡 Note:Combined values: [4,4]. Alice picks first stone (gains 1), Bob picks second (gains 1). Alice: 1, Bob: 1. Tie, so result is 0. Wait - let me recalculate: If Alice picks stone 0 (A:1,B:3), then Bob picks stone 1 (A:3,B:1) and gets 1 point. Alice:1, Bob:1 = tie. But if Alice picks stone 1 first (A:3,B:3), Bob gets stone 0 (A:1,B:3) and gets 3. Alice:3, Bob:3 = tie. Actually both lead to tie, so result is 0.
Example 2 — Different Values
$Input:aliceValues = [1,2], bobValues = [3,1]
›Output:0
💡 Note:Combined values: stone 0 has sum 4, stone 1 has sum 3. Alice picks stone 0 (gains 1), Bob picks stone 1 (gains 1). Alice: 1, Bob: 1. Draw.
Example 3 — Clear Winner
$Input:aliceValues = [2,4,3], bobValues = [1,1,2]
›Output:1
💡 Note:Combined values: [3,5,5]. Sorted order: stone 1 (sum 5), stone 2 (sum 5), stone 0 (sum 3). Alice picks stone 1 (gains 4), Bob picks stone 2 (gains 2), Alice picks stone 0 (gains 2). Alice: 6, Bob: 2. Alice wins.
The key insight is that picking a stone gives you points AND denies your opponent their points for that stone. The optimal strategy is to sort stones by combined value (aliceValues[i] + bobValues[i]) and have players pick greedily from highest impact stones first. Best approach uses greedy sorting in O(n log n) time, O(n) space.
Common Approaches
✓
Brute Force - Game Tree Exploration
⏱️ Time: O(n!)
Space: O(n)
Use recursion to simulate the game where each player alternately picks stones optimally. At each turn, try all remaining stones and choose the one that leads to the best outcome for the current player.
Greedy - Combined Value Priority
⏱️ Time: O(n log n)
Space: O(n)
The key insight is that when a player picks a stone, they gain their value for it AND prevent the opponent from getting their value. So the total impact of picking stone i is aliceValues[i] + bobValues[i]. Sort by this combined value and simulate optimal play.
Brute Force - Game Tree Exploration — Algorithm Steps
Recursively simulate the game for each player's turn
For each turn, try picking every remaining stone
Choose the stone that maximizes current player's advantage
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Initial State
All stones available, Alice's turn
2
Recursive Search
Try each stone, simulate opponent's optimal response
3
Backtrack
Return best result for current player
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int gameResult(bool* used, int* aliceValues, int* bobValues, int n,
int aliceScore, int bobScore, bool isAliceTurn) {
bool allUsed = true;
for (int i = 0; i < n; i++) {
if (!used[i]) {
allUsed = false;
break;
}
}
if (allUsed) {
if (aliceScore > bobScore) return 1;
else if (bobScore > aliceScore) return -1;
else return 0;
}
if (isAliceTurn) {
int bestResult = -2;
for (int i = 0; i < n; i++) {
if (!used[i]) {
used[i] = true;
int result = gameResult(used, aliceValues, bobValues, n,
aliceScore + aliceValues[i], bobScore, false);
used[i] = false;
if (result > bestResult) {
bestResult = result;
}
}
}
return bestResult;
} else {
int bestResult = 2;
for (int i = 0; i < n; i++) {
if (!used[i]) {
used[i] = true;
int result = gameResult(used, aliceValues, bobValues, n,
aliceScore, bobScore + bobValues[i], true);
used[i] = false;
if (result < bestResult) {
bestResult = result;
}
}
}
return bestResult;
}
}
int solution(int* aliceValues, int* bobValues, int n) {
bool* used = (bool*)calloc(n, sizeof(bool));
int result = gameResult(used, aliceValues, bobValues, n, 0, 0, true);
free(used);
return result;
}
int parseArray(const char* str, int* arr) {
int size = 0;
const char* p = str;
// Find opening bracket
while (*p && *p != '[') p++;
if (*p != '[') return 0;
p++;
// Parse numbers
while (*p && *p != ']') {
// Skip whitespace and commas
while (*p == ' ' || *p == ',') p++;
if (*p == ']' || *p == '\0') break;
// Parse number using strtol
char* endptr;
long val = strtol(p, &endptr, 10);
if (endptr != p) {
arr[size++] = (int)val;
p = endptr;
} else {
break;
}
}
return size;
}
int main() {
char line1[1000], line2[1000];
fgets(line1, sizeof(line1), stdin);
fgets(line2, sizeof(line2), stdin);
// Remove newlines
line1[strcspn(line1, "\n")] = '\0';
line2[strcspn(line2, "\n")] = '\0';
int aliceValues[100], bobValues[100];
int n1 = parseArray(line1, aliceValues);
int n2 = parseArray(line2, bobValues);
printf("%d\n", solution(aliceValues, bobValues, n1));
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(n!)
Each player can choose from n, n-1, n-2... stones, leading to n! possible game sequences
n
2n
⚡ Linearithmic
Space Complexity
O(n)
Recursion depth equals number of stones, plus array to track used stones
n
2n
⚡ Linearithmic Space
25.4K Views
MediumFrequency
~25 minAvg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.