移除石子的最大得分【LC1753】
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.
就是说 做出来了也觉得很amazing
- 思路:找找规律,贪心一下
局部最优:尽可能多匹配几次
全局最优:使最终得分最大
。当对a,b,c进行升序排序后,如果a+b≥c,应先优先让a和b 去匹配,匹配的次数为a+b−c,得分为count=⌈(a+b−c)/2⌉
。当a+b<c时,最多只能取a+b个石头
。最终的得分即为count+a+b
- 实现
class Solution { public int maximumScore(int a, int b, int c) { int[] stones = {a, b ,c}; Arrays.sort(stones); a = stones[0]; b = stones[1]; c = stones[2]; int count = 0; // 先取ab,使a + b <= c while (a + b > c){ count++; a--; b--; } // 先取ac,再取bc return count + a + b; } }
。复杂度
- 时间复杂度:O ( 1 )
- 空间复杂度:O ( 1 )