aboutsummaryrefslogtreecommitdiff
path: root/stone_game2.py
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2024-08-19 18:22:13 -0600
committerJack Sangdahl <[email protected]>2024-08-19 18:22:13 -0600
commitb756e65c613e0f145c671d089e30b62ae6f63959 (patch)
treebe77c9d693390c9290a26f36cac54dcdd57fc879 /stone_game2.py
parent020819074443b820d3195c1a36698b26b27c04a0 (diff)
downloadleetcode-b756e65c613e0f145c671d089e30b62ae6f63959.tar.gz
leetcode-b756e65c613e0f145c671d089e30b62ae6f63959.zip
1140. stone game 2
Diffstat (limited to 'stone_game2.py')
-rw-r--r--stone_game2.py42
1 files changed, 42 insertions, 0 deletions
diff --git a/stone_game2.py b/stone_game2.py
new file mode 100644
index 0000000..46ead18
--- /dev/null
+++ b/stone_game2.py
@@ -0,0 +1,42 @@
+# 1140. Stone Game II
+
+"""
+alice and bob continue their games with piles of stones. there are a number
+of piles arranged in a row, and each pile has a positive integer number of
+stones 'piles[i]'. the objective of the game is to end with the most stones.
+alice and bob take turns, with alice starting first. initiall, 'M = 1'. on
+each player's turn, that player can take all the stones on the 'X' remaining
+piles, where '1 <= X <= 2M'. then, we set 'M = max(M, X)'. the game continues
+until all the stones have been take. assuming alice and bob play optimally,
+return maximum stones alice can get.
+"""
+
+
+class Solution(object):
+ def stoneGameII(self, piles):
+ """
+ :type piles: List[int]
+ :rtype: int
+ """
+
+ def dp(x, y, z):
+ if y == len(piles):
+ return 0
+ if x == 0:
+ curr, res = 0, float("-inf")
+ for i in range(1, min(z * 2, len(piles) - y) + 1):
+ curr += piles[y + i - 1]
+ res = max(res, curr + dp(1, y + i, max(i, z)))
+ else:
+ res = float("inf")
+ for i in range(1, min(z * 2, len(piles) - y) + 1):
+ res = min(res, dp(0, y + i, max(i, z)))
+ return res
+
+ return dp(0, 0, 1)
+
+
+if __name__ == "__main__":
+ obj = Solution()
+ print(obj.stoneGameII(piles=[2, 7, 9, 4, 4]))
+ print(obj.stoneGameII(piles=[1, 2, 3, 4, 5, 100]))