📜  装满 K 杯所需的最少瓶子数

📅  最后修改于: 2021-10-26 05:20:37             🧑  作者: Mango

给定 N 个装有水的玻璃杯,以及每个玻璃杯容量的列表 A。任务是找出恰好装满 K 个玻璃杯所需的最少瓶子数。每瓶容量为100个单位。

例子:

方法:要准确填写K个眼镜,取容量最小的K个眼镜。所以对于这种排序给定容量的列表。最终答案将是(第 1 k 杯容量的总和) / (1 瓶容量)的上限值。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// function to calculate minimum glasses
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 = ceil((double)sum /
                            (double)100);
  
    return ans;
}
 
// Driver code
int main()
{
 
    int n = 4;
    int k = 3;
    int a[] = { 200, 150, 140, 300 };
    sort(a, a+n);
    cout << Min_glass(n, k, a);
 
    return 0;
}
 
// This code is conntributed by target_2.


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


Javascript


输出:
5

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程