1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
from typing import List
class Solution: def game(self, piles: List[int]) -> int: if not piles: return 0 n = len(piles) dp = [[[0] * 2 for _ in range(n)] for _ in range(n)] for i in range(n): dp[i][i][0] = piles[i] for gap in range(1, n): for i in range(n - gap): j = i + gap left = dp[i + 1][j][1] + piles[i] right = dp[i][j - 1][1] + piles[j] if left > right: dp[i][j][0] = left dp[i][j][1] = dp[i + 1][j][0] else: dp[i][j][0] = right dp[i][j][1] = dp[i][j - 1][0] return dp[0][n - 1][0] - dp[0][n - 1][1]
def main(): sol = Solution()
piles = [1, 100, 3] res = sol.game(piles) print(res)
if __name__ == '__main__': main()
|