Skip to content

Commit e187c7c

Browse files
authored
Create 0877-stone-game.cpp
1 parent a17f1f8 commit e187c7c

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

cpp/0877-stone-game.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Alice and Bob play a game with piles of stones. There are an even number of piles arranged
3+
in a row, and each pile has a positive integer number of stones piles[i].
4+
5+
The objective of the game is to end with the most stones. The total number of stones across
6+
all the piles is odd, so there are no ties.
7+
8+
Alice and Bob take turns, with Alice starting first. Each turn, a player takes the entire pile
9+
of stones either from the beginning or from the end of the row. This continues until there are
10+
no more piles left, at which point the person with the most stones wins.
11+
12+
Assuming Alice and Bob play optimally, return true if Alice wins the game, or false if Bob wins.
13+
14+
Ex: Input: piles = [5,3,4,5]
15+
Output: true
16+
Explanation:
17+
Alice starts first, and can only take the first 5 or the last 5.
18+
Say she takes the first 5, so that the row becomes [3, 4, 5].
19+
If Bob takes 3, then the board is [4, 5], and Alice takes 5 to win with 10 points.
20+
If Bob takes the last 5, then the board is [3, 4], and Alice takes 4 to win with 9 points.
21+
This demonstrated that taking the first 5 was a winning move for Alice, so we return true.
22+
23+
Space: O(n/2)
24+
Time : O(1)
25+
*/
26+
27+
28+
class Solution {
29+
public:
30+
bool stoneGame(vector<int>& piles) {
31+
int alice = 0, bob = 0, size = piles.size();
32+
for(int i = 0 ; i < size/2; i++) {
33+
alice = alice + max( piles[i], piles[size - 1- i] );
34+
bob = bob + min( piles[i], piles[size - 1- i] );
35+
}
36+
if(alice > bob)
37+
return true;
38+
return false;
39+
}
40+
};

0 commit comments

Comments
 (0)