algorithm-in-python/dynamicProgramming/last-stone-weight.py

34 lines
1.2 KiB
Python
Raw Normal View History

2019-06-02 23:16:01 +08:00
#coding: utf-8
''' mbinary
#######################################################################
# File : last-stone-weight.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
# Blog: https://mbinary.xyz
# Github: https://github.com/mbinary
# Created Time: 2019-05-28 23:30
# Description:
leetcode 1049: https://leetcode-cn.com/problems/last-stone-weight-ii/
有一堆石头每块石头的重量都是正整数
每一回合从中选出任意两块石头然后将它们一起粉碎假设石头的重量分别为 x y x <= y那么粉碎的可能结果如下
如果 x == y那么两块石头都会被完全粉碎
如果 x != y那么重量为 x 的石头将会完全粉碎而重量为 y 的石头新重量为 y-x
最后最多只会剩下一块石头返回此石头最小的可能重量如果没有石头剩下就返回 0
#######################################################################
'''
2020-04-15 12:28:20 +08:00
2019-06-02 23:16:01 +08:00
class Solution:
def lastStoneWeightII(self, stones: List[int]) -> int:
sm = sum(stones)
ans = sm//2
dp = [0]*(ans+1)
for x in stones:
2020-04-15 12:28:20 +08:00
for j in range(ans, x-1, -1):
dp[j] = max(dp[j], dp[j-x]+x)
2019-06-02 23:16:01 +08:00
return sm-2*dp[ans]