桌上有 n 堆力扣币,每堆的数量保存在数组 coins 中。我们每次可以选择任意一堆,拿走其中的一枚或者两枚,求拿完所有力扣币的最少次数。
示例 1:
输入:[4,2,1]
输出:4
解释:第一堆力扣币最少需要拿 2 次,第二堆最少需要拿 1 次,第三堆最少需要拿 1 次,总共 4 次即可拿完。
示例 2:
输入:[2,3,10]
输出:8
限制:
1 <= n <= 4
1 <= coins[i] <= 10
==============
方法一
class Solution {
public:
int minCount(vector<int>& coins) {
int sum = 0;
for (auto coin : coins) {
sum += (coin + 1) / 2;
}
return sum;
}
};
方法二
class Solution {
public:
int minCount(vector<int>& coins) {
return accumulate(coins.begin(), coins.end(), 0, [](int a, int b){return a + (b + 1) / 2; });
}
};
该博客讨论了如何解决LeetCode中的一道问题,即在给定一定数量的力扣币堆时,找到拿完所有力扣币的最小次数。提供了两种方法,一种是通过循环累加,另一种使用累积函数。示例展示了对于不同输入数组的解决方案,并给出了限制条件。
683

被折叠的 条评论
为什么被折叠?



