Algorithm to take coins

There are n piles of coins on the table, and the number of each pile is stored in the array arr. We can choose any pile each time, take one or two of them, and ask for the minimum number of times to take all the coins.

Example 1:

Input: [4,2,1]

Output: 4

Explanation: The first pile of coins needs to be picked up at least twice, the second pile needs to be picked up at least once, and the third pile needs to be picked up at least once. A total of 4 times can be used.

Example 2:

Input: [
2,3,10 ] int TakeCoin(vector& coin)
{ int cnt = 0; for (auto c: coin) { cnt += c / 2; // Take two coins for the first few times cnt += c % 2; // Not two, take one } return cnt; } output: 8








Algorithm 1:

int minCount(int* arr, int num)
{
    
    
	int i, count = 0;	
	for (i = 0;i < num;i++) 
	{
    
    
		if (arr[i] % 2 != 0)//不能整除  次数+1
		{
    
    
			count += (arr[i] + 1) / 2;
		}
		else {
    
       //整除
			count += arr[i] / 2;
		}
	}
	return count;
}

Algorithm 2:

int TakeCoin(vector<int>& coin)
{
    
    
	int cnt = 0;
	for (auto c : coin)
	{
    
    
		cnt += c / 2;		// 前几次都拿两枚硬币
		cnt += c % 2;		// 不够两枚,拿一枚
	}
	return cnt;
}

Test test cases:

int main()
{
    
    
	vector<int> coin1 = {
    
     4,2,1 };
	auto ret1 = TakeCoin(coin1);

	vector<int> coin2 = {
    
     2,3,10 };
	auto ret2 = TakeCoin(coin2);

	cout << ret1 << "  " << ret2  << endl;

	return 0;
}

Guess you like

Origin blog.csdn.net/Gunanhuai/article/details/109126708