Day 48 of LeetCode
Evelyn Liu
1 min read
Documenting LeetCode solving.
Q125
Hard. DP
Reverse thinking.
class Solution:
def maxCoins(self, nums: List[int]) -> int:
nums = [1] + nums + [1]
dp = {}
def dfs(l, r):
if l > r:
return 0
if (l, r) in dp:
return dp[(l, r)]
dp[(l, r)] = 0
# i is last popped
for i in range(l, r + 1):
coins = nums[l - 1] * nums[i] * nums[r + 1]
coins += dfs(l, i - 1) + dfs(i + 1, r)
dp[(l, r)] = max(dp[(l, r)], coins)
return dp[(l, r)]
return dfs(1, len(nums) - 2)
0
Subscribe to my newsletter
Read articles from Evelyn Liu directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by