给定两个整数N和C (代表男孩和糖果的数量)和整数K ,任务是计算任何男孩接收的最大和最小糖果数量,以使它们之间的差为K。
例子:
Input: N = 4, C = 12, K = 3
Output:
Maximum = 5
Minimum = 2
Explanation:
Distribute the {2, 2, 3, 5} candies among N (= 4) boys.
Therefore, the difference between the maximum and minimum is 5 – 2 = 3 (= K).
Input: N = 2, C = 8, K = 2
Output:
Maximum = 5
Minimum = 3.
方法:可以根据以下观察结果解决给定问题:
- 如果K> = C:所有C糖果都可以分配给第一个男孩。因此,糖果的最大数量为C ,最小数量为0 。
- 否则,将糖果分发给男孩,使最大和最小计数保持≤K。
Illustration: Refer to the table below to observe the distribution pattern of candies.
Boy A |
Boy B |
Boy C |
Difference |
K |
0 |
0 |
K |
K |
1 |
1 |
K-1 |
K+1 |
1 |
1 |
K |
K+1 |
2 |
2 |
K-1 |
K+2 |
2 |
2 |
K |
Initially, distribute K candies to the 1st boy.
Now, distribute remaining C – K candies to each boy line-wise starting form 2nd boy to Nth boy and then, again from 1st to Nth and so on.
请按照以下步骤解决问题:
- 初始化两个变量,例如最大和最小,以存储男孩可以拥有的最大和最小糖果数。
- 如果N = 1:设置最大值= C和最小值= C
- 如果K> = C:设置最大值= C且最小值= 0
- 否则,如果K
,则将最大值= K并将最小值= 0设置。现在,请按照以下步骤操作: - 初始化一个变量,例如remain_candy,并将其设置为C –K。
- 将( remain_candy / N )加到最大值和最小值。
- 如果( rest_candy%N == N-1 ),则增加最小值。
- 打印最小值和最大值。
下面是上述方法的实现:
C++
// C++ program for
// the above approach
#include
using namespace std;
// Function to calculate the
// maximum and minimum number
// of candies a boy can possess
int max_min(int N, int C, int K)
{
int maximum, minimum;
if (N == 1) {
// All candies will be
// given to one boy
maximum = minimum = C;
}
else if (K >= C) {
// All the candies will
// be given to 1 boy
maximum = C;
minimum = 0;
}
else {
// Give K candies to 1st
// boy initially
maximum = K;
minimum = 0;
// Count remaining candies
int remain_candy = C - K;
maximum += remain_candy / N;
minimum = remain_candy / N;
// If the last candy of remaining candies
// is given to the last boy, i.e Nth boy
if (remain_candy % N == N - 1) {
// Increase minimum count
minimum++;
}
}
cout << "Maximum = " << maximum
<< endl;
cout << "Minimum = " << minimum;
return 0;
}
// Driver Code
int main()
{
int N = 4;
int C = 12;
int K = 3;
max_min(N, C, K);
return 0;
}
Maximum = 5
Minimum = 2
时间复杂度: O(1)
辅助空间: O(1)