LCP 06.拿硬币(LEETCODE)
LCP 06.拿硬币
桌上有 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 n = coins.size(), count = 0;
for(int i = 0; i < n; i ++){
if(coins[i] % 2 == 0){
count = count + coins[i] /2;
}
else{
count = count + (coins[i] + 1) / 2;
}
}
return count;
}
};
其他代码
class Solution {
public:
int minCount(vector<int>& coins) {
int count=0;
for(int i:coins)
{
count+=(i+1)/2;
}
return count;
}
};
作者:forwardli
来源:力扣(LeetCode)
class Solution {
public:
int minCount(vector<int>& coins) {
int count = 0;
for (int a : coins) count += (a+1)>>1; //右移相当于除以二
return count;
}
};
作者:TheBadZhang
来源:力扣(LeetCode)

浙公网安备 33010602011771号