【LetMeFly】LCP 06. Get coins
Leetcode question link: https://leetcode.cn/problems/na-ying-bi/
There are n
piles of coins on the table, and the number of each pile is stored in an array coins
. We can choose any pile each time, take away one or two of them, and find the minimum number of times to deduct coins after taking all the coins.
Example 1:
enter:
[4,2,1]
Output:4
Explanation: The first pile of force coins needs to be taken at least 2 times, the second pile needs to be taken at least 1 time, the third pile needs to be taken at least 1 time, and a total of 4 times can be obtained.
Example 2:
enter:
[2,3,10]
Output:8
limit:
1 <= n <= 4
1 <= coins[i] <= 10
Method 1: Traverse
If you can get 1 or 2 coins each time, you must get as many as possible. For a bunch of nnn coins, the minimum number of times required is⌈ n 2 ⌉ \lceil \frac{n}2 \rceil⌈2n⌉。
Tip: ⌊ n + 1 2 ⌋ = ⌈ n 2 ⌉ \lfloor\frac{n+1}2\rfloor=\lceil \frac{n}2 \rceil⌊2n+1⌋=⌈2n⌉
- Time complexity O ( len ( coins ) ) O(len(coins))O(len(coins))
- Space complexity O ( 1 ) O(1)O(1)
AC code
C++
class Solution {
public:
int minCount(vector<int>& coins) {
int ans = 0;
for (int t : coins) {
ans += (t + 1)/ 2;
}
return ans;
}
};
Python
# from typing import List
class Solution:
def minCount(self, coins: List[int]) -> int:
return sum((i + 1) // 2 for i in coins)
The article is published simultaneously on CSDN. It is not easy to be original. Please attach the link to the original article after reprinting with the author's consent ~
Tisfy: https://letmefly.blog.csdn.net/article/details/133070027