给定N杯有水,并且每个杯子的容量A。任务是找到可准确装满K杯所需的最少瓶子数。每个瓶子的容量为100个单位。
例子:
Input: N = 4, K = 3, arr[] = {200, 150, 140, 300}
Output: 5
We have to fill out exactly 3 glasses.
So we fill out 140, 150, 200 whose sum is 490 so we need 5 bottles for this.
Input: N = 5, K = 4, arr[] = {1, 2, 3, 2, 1}
Output: 1
方法:要准确地填写K杯,请拿最小容量的K杯。因此,对于这种排序,列出了给定的容量。最终答案将是(第一个k杯容量总和)/(一瓶容量)的上限值。
下面是上述方法的实现:
C/C++
// C++ implementation of the above approach
#include
using namespace std;
// function to calculate minimum glasses
int Min_glass(int n, int k, int a[])
{
// sort the array based on
// their capacity
sort(a, a + n);
int sum = 0;
// taking sum of capacity
// of first k glasses
for (int i = 0; i < k; i++)
sum += a[i];
// calculate the answer
int ans = ceil((double)sum / (double)100);
return ans;
}
// Driver code
int main()
{
int n = 4;
int k = 3;
int a[] = { 200, 150, 140, 300 };
cout << Min_glass(n, k, a);
return 0;
}
Java
// Java implementation of the
// above approach
import java.util.*;
class GFG
{
// function to calculate minimum glasses
public static double Min_glass(int n, int k,
int[] a)
{
// sort the array based on
// their capacity
int sum = 0;
// taking sum of capacity
// of first k glasses
for (int i = 0; i < k; i++)
sum += a[i];
// calculate the answer
double ans = Math.ceil((double)sum /
(double)100);
return ans;
}
// Driver code
public static void main(String[] args)
{
int n = 4;
int k = 3;
int[] a = { 200, 150, 140, 300 };
Arrays.sort(a);
System.out.println(Min_glass(n, k, a));
}
}
// This code is contributed by mits
Python3
# Python3 implementation of the above approach
from math import ceil
# Function to calculate minimum glasses
def Min_glass(n, k, a):
# sort the array based on their capacity
a.sort()
# calculate the answer
return ceil(sum(a[:k]) / 100)
# Driver code
if __name__ == "__main__":
n, k = 4, 3
a = [200, 150, 140, 300]
print(Min_glass(n, k, a))
# This code is contributed by Rituraj Jain
C#
// C# implementation of the
// above approach
using System;
class GFG
{
// function to calculate minimum glasses
public static double Min_glass(int n, int k,
int []a)
{
// sort the array based on
// their capacity
int sum = 0;
// taking sum of capacity
// of first k glasses
for (int i = 0; i < k; i++)
sum += a[i];
// calculate the answer
double ans = Math.Ceiling((double)sum /
(double)100);
return ans;
}
// Driver code
public static void Main()
{
int n = 4;
int k = 3;
int[] a = { 200, 150, 140, 300 };
Array.Sort(a);
Console.WriteLine(Min_glass(n, k, a));
}
}
// This code is contributed
// by Soumik Mondal
PHP
输出:
5