Skip to content

Commit ec412c9

Browse files
committed
day 5
1 parent 05a8d5e commit ec412c9

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
/*
2+
Stone Game
3+
==========
4+
5+
Alex and Lee play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].
6+
7+
The objective of the game is to end with the most stones. The total number of stones is odd, so there are no ties.
8+
9+
Alex and Lee take turns, with Alex starting first. Each turn, a player takes the entire pile of stones from either the beginning or the end of the row. This continues until there are no more piles left, at which point the person with the most stones wins.
10+
11+
Assuming Alex and Lee play optimally, return True if and only if Alex wins the game.
12+
13+
Example 1:
14+
Input: piles = [5,3,4,5]
15+
Output: true
16+
Explanation:
17+
Alex starts first, and can only take the first 5 or the last 5.
18+
Say he takes the first 5, so that the row becomes [3, 4, 5].
19+
If Lee takes 3, then the board is [4, 5], and Alex takes 5 to win with 10 points.
20+
If Lee takes the last 5, then the board is [3, 4], and Alex takes 4 to win with 9 points.
21+
This demonstrated that taking the first 5 was a winning move for Alex, so we return true.
22+
23+
Constraints:
24+
2 <= piles.length <= 500
25+
piles.length is even.
26+
1 <= piles[i] <= 500
27+
sum(piles) is odd.
28+
*/
29+
30+
class Solution {
31+
public:
32+
bool stoneGame(vector<int>& A) {
33+
int alice = 0, bob = 0;
34+
int turn = 0;
35+
36+
int i = 0, j = A.size()-1;
37+
while(i <= j) {
38+
if(turn == 0) {
39+
if(A[i] > A[j]) {
40+
alice += A[i];
41+
i++;
42+
}
43+
else {
44+
alice += A[j];
45+
j--;
46+
}
47+
}
48+
49+
else {
50+
if(A[i] > A[j]) {
51+
bob += A[i];
52+
i++;
53+
}
54+
else {
55+
bob += A[j];
56+
j--;
57+
}
58+
}
59+
}
60+
61+
return alice > bob;
62+
}
63+
};
64+
65+

Leetcode Daily Challenge/August-2021/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@
66
| 2. | [Two Sum](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3836/) | [cpp](./02.%20Two%20Sum.cpp) |
77
| 3. | [Subsets II](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3837/) | [cpp](./03.%20Subsets%20II.cpp) |
88
| 4. | [Path Sum II](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3838/) | [cpp](./04.%20Path%20Sum%20II.cpp) |
9+
| 5. | [Stone Game](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3870/) | [cpp](./05.%20Stone%20Game.cpp) |

0 commit comments

Comments
 (0)