leetcode 1753. Maximum Score From Removing Stones(python)

描述

You are playing a solitaire game with three piles of stones of sizes a​​​​​​, b,​​​​​​ and c​​​​​​ respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves).

Given three integers a​​​​​, b,​​​​​ and c​​​​​, return the maximum score you can get.

Example 1:

Input: a = 2, b = 4, c = 6
Output: 6
Explanation: The starting state is (2, 4, 6). One optimal set of moves is:
- Take from 1st and 3rd piles, state is now (1, 4, 5)
- Take from 1st and 3rd piles, state is now (0, 4, 4)
- Take from 2nd and 3rd piles, state is now (0, 3, 3)
- Take from 2nd and 3rd piles, state is now (0, 2, 2)
- Take from 2nd and 3rd piles, state is now (0, 1, 1)
- Take from 2nd and 3rd piles, state is now (0, 0, 0)
There are fewer than two non-empty piles, so the game ends. Total: 6 points.

Example 2:

Input: a = 4, b = 4, c = 6
Output: 7
Explanation: The starting state is (4, 4, 6). One optimal set of moves is:
- Take from 1st and 2nd piles, state is now (3, 3, 6)
- Take from 1st and 3rd piles, state is now (2, 3, 5)
- Take from 1st and 3rd piles, state is now (1, 3, 4)
- Take from 1st and 3rd piles, state is now (0, 3, 3)
- Take from 2nd and 3rd piles, state is now (0, 2, 2)
- Take from 2nd and 3rd piles, state is now (0, 1, 1)
- Take from 2nd and 3rd piles, state is now (0, 0, 0)
There are fewer than two non-empty piles, so the game ends. Total: 7 points.

Example 3:

Input: a = 1, b = 8, c = 8
Output: 8
Explanation: One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.
After that, there are fewer than two non-empty piles, so the game ends.

Note:

1 <= a, b, c <= 10^5

解析

根据题意,只需要自己列几个例子就能找出其中的规律,将 a,b,c 按照从小到大的的顺序进行排序得到 l ,然后比较 l[:2] 和 l[2] 的大小:
如果 l[:2] 大于 l[2] ,则结果是 sum(l)/2 。在举例子的过程中会发现如果 sum(l) 为奇数,最后都会得到类似 [1,0,0] 的石头堆组合,如果 sum(l) 为偶数,最后都会得到 [0,0,0] 的石头堆组合,在任意两个石头堆的减一游戏过程中,sum(l) 每轮都会减二,所以可以理解为这种情况就是对 sum(l) 进行对 2 的取商取整。
否则则是 sum(l[:2]) 。因为 sum(l[:2]) 小于等于 l[2],所以在每轮从 (第三堆+第一堆或第二堆)的组合中进行石头的减一游戏,结果肯定是 sum(l[:2]) 。

解答

class Solution(object):
    def maximumScore(self, a, b, c):
        """
        :type a: int
        :type b: int
        :type c: int
        :rtype: int
        """
        l = sorted([a,b,c])
        if l[0]+l[1] > l[2]:
            return sum(l)/2
        return  l[0]+l[1]

运行结果

Runtime: 8 ms, faster than 100.00% of Python online submissions for Maximum Score From Removing Stones.
Memory Usage: 13.4 MB, less than 70.78% of Python online submissions for Maximum Score From Removing Stones.

原题链接:https://leetcode.com/problems/maximum-score-from-removing-stones/

猜你喜欢

转载自blog.csdn.net/wang7075202/article/details/114100527