Skip to content

Latest commit

 

History

History

LCP 06. 拿硬币

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 

题目描述

桌上有 n 堆力扣币,每堆的数量保存在数组 coins 中。我们每次可以选择任意一堆,拿走其中的一枚或者两枚,求拿完所有力扣币的最少次数。

示例 1:

输入:[4,2,1]

输出:4

解释:第一堆力扣币最少需要拿 2 次,第二堆最少需要拿 1 次,第三堆最少需要拿 1 次,总共 4 次即可拿完。

示例 2:

输入:[2,3,10]

输出:8

限制:

  • 1 <= n <= 4
  • 1 <= coins[i] <= 10

解法

Python3

class Solution:
    def minCount(self, coins: List[int]) -> int:
        return sum((coin + 1) // 2 for coin in coins)

Java

class Solution {
    public int minCount(int[] coins) {
        int ans = 0;
        for (int coin : coins) {
            ans += (coin + 1) / 2;
        }
        return ans;
    }
}

C++

class Solution {
public:
    int minCount(vector<int>& coins) {
        int ans = 0;
        for (int coin : coins) ans += (coin + 1) / 2;
        return ans;
    }
};

Go

func minCount(coins []int) int {
	ans := 0
	for _, coin := range coins {
		ans += (coin + 1) / 2
	}
	return ans
}

C

int minCount(int* coins, int coinsSize) {
    int res = 0;
    for (int i = 0; i < coinsSize; i++) {
        int coin = coins[i];
        if (coin % 2 == 1) {
            res++;
        }
        res += coin / 2;
    }
    return res;
}

TypeScript

function minCount(coins: number[]): number {
    let ans = 0;
    for (const coin of coins) {
        ans += Math.floor((coin + 1) / 2);
    }
    return ans;
}

...