问题描述
问题解决者找到了一个新的编码岛,并将其命名为Philaland。这些聪明的人被赋予一项任务,通过分发具有不同价值的各种硬币来简化在岛上的物品购买。曼尼什(Manish)提出了一个解决方案,如果我们使硬币的类别从$ 1开始直到Island上商品的最高价格,那么我们可以轻松地购买任何商品。他添加了以下示例来证明自己的观点。
让我们假设一个项目的最高价格是5 $,那么我们可以制作{$ 1,$ 2,$ 3,$ 4,$ 5}的硬币来购买从$ 1到$ 5的任何项目。现在,Manisha是一位敏锐的观察者,他建议我们实际上可以减少所需硬币的数量,并进行以下分配{$ 1,$ 2,$ 3}。据他说,任何物品都可以一次购买,价格从$ 1到$ 5不等。每个人都给他们留下了深刻的印象。
您的任务是帮助Manisha在Philaland中以任意最高价格得出最小面额的货币。
例子:
Input: N = 10
Output: 4
Explanation:
According to Manish {$1, $2, $3, … $10} must be distributed.
But as per Manisha only {$1, $2, $3, $4} coins are enough to purchase any item ranging from $1 to $10. Hence minimum is 4. Likewise denominations could also be {$1, $2, $3, $5}. Hence answer is still 4.
Input: N = 5
Output: 3
Explanation:
According to Manish {$1, $2, $3, $4, $5} must be distributed.
But as per Manisha only {$1, $2, $3} coins are enough to purchase any item ranging from $1 to $5. Hence minimum is 3. Likewise denominations could also be {$1, $2, $4}. Hence answer is still 3.
方法:对该问题的主要观察是,任何数字都可以表示为二的幂。因此,最低面额要求为–
例如:
For N = 12,
If we choose the denominations as {1, 2, 4, 8}
Then every number up to 12 can be represented as –
1 ==> 1
2 ==> 2
3 ==> 2 + 1
4 ==> 4
5 ==> 4 + 1
6 ==> 4 + 2
7 ==> 4 + 2 + 1
8 ==> 8
9 ==> 8 + 1
10 ==> 8 + 2
11 ==> 8 + 2 + 1
12 ==> 8 + 4
下面是上述方法的实现:
C++
// C++ implementation to find the
// minimum number of denominations
// required for any number
#include
using namespace std;
// Function to find the minimum
// number of denomminations required
int findMinDenomin(int n)
{
return log2(n) + 1;
}
// Driver Code
int main()
{
int n = 10;
// Function Call
cout << findMinDenomin(n);
return 0;
}
Java
// Java implementation to find the
// minimum number of denominations
// required for any number
import java.io.*;
class GFG
{
// Function to find the minimum
// number of denomminations required
static int findMinDenomin(int n)
{
return ((int)(Math.log(n)/Math.log(2))+1);
}
// Driver Code
public static void main (String[] args)
{
int n = 10;
// Function Call
System.out.println(findMinDenomin(n));
}
}
// This code is contributed by avanitrachhadiya2155
Python3
# Python3 implementation to find the
# minimum number of denominations
# required for any number
from math import log2, floor
# Function to find the minimum
# number of denomminations required
def findMinDenomin(n):
return log2(n) + 1
# Driver Code
if __name__ == '__main__':
n = 10
# Function call
print(floor(findMinDenomin(n)))
# This code is contributed by mohit kumar 29
C#
// C# implementation to find the
// minimum number of denominations
// required for any number
using System;
class GFG
{
// Function to find the minimum
// number of denomminations required
static int findMinDenomin(int n)
{
return ((int)(Math.Log(n)/Math.Log(2))+1);
}
// Driver Code
static public void Main ()
{
int n = 10;
// Function Call
Console.WriteLine(findMinDenomin(n));
}
}
// This code is contributed by rag2127
4
性能分析:
- 时间复杂度: O(logN)
- 辅助空间: O(1)