파비의 매일매일 공부기록

2023.05.26 Today's Challenge 본문

Problem Solving/LeetCode

2023.05.26 Today's Challenge

fabichoi 2023. 5. 26. 23:45

https://leetcode.com/problems/stone-game-ii/

 

Stone Game II - LeetCode

Can you solve this real interview question? 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

leetcode.com

근래에 본 DP 문제 중 제일 복잡했던 듯.

class Solution:
    def stoneGameII(self, piles: List[int]) -> int:
        n = len(piles)
        dp = [[[-1] * (n+1) for i in range(n+1)] for p in range(0, 2)]

        def f(p, i, m):
            if i == n:
                return 0
            if dp[p][i][m] != -1:
                return dp[p][i][m]
            res = -1
            if p == 1:
                res = 1000000
            s = 0
            for x in range(1, min(2*m, n-i) + 1):
                s += piles[i+x-1]
                if p == 0:
                    res = max(res, s + f(1, i+x, max(m, x)))
                else:
                    res = min(res, f(0, i+x, max(m, x)))
            dp[p][i][m] = res
            return res
        
        return f(0, 0, 1)
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

2023.05.28 Today's Challenge  (0) 2023.05.28
2023.05.27 Today's Challenge  (0) 2023.05.27
2023.05.25 Today's Challenge  (0) 2023.05.25
2023.05.24 Today's Challenge  (0) 2023.05.24
2023.05.23 Today's Challenge  (0) 2023.05.23
Comments