📜  当一个项目总成本的其他项目免费时,获取最大项目

📅  最后修改于: 2021-04-29 10:17:13             🧑  作者: Mango

给定“ N”项的价格清单。一个人只能购买任何价格的一件物品,而他可以免费获得其他物品,使得其余物品的总价不超过所购买物品的价格。任务是找到此人可以拥有的最大物品数。

例子:

方法:

下面是上述方法的实现:

C++
// C++ implementation of 
// the above approach 
#include 
using namespace std;
  
// Function to count the 
// total number of items 
int  items(int n, int a[]){ 
  
    // Sort the prices 
    sort(a,a+n);
  
    // Choose the last element 
    int z = a[n-1]; 
  
    // Initial count of item 
    int x = 1;
  
    // Sum to keep track of 
    // the total price 
    // of free items 
    int s = 0;
    for (int i=0;i


Java
// Java implementation of 
// the above approach
import java.util.Arrays; 
import java.io.*;
  
class GFG {
  
// Function to count the 
// total number of items 
static int items(int n, int a[]){ 
  
    // Sort the prices 
    Arrays.sort(a);
  
    // Choose the last element 
    int z = a[n-1]; 
  
    // Initial count of item 
    int x = 1;
  
    // Sum to keep track of 
    // the total price 
    // of free items 
    int s = 0;
    for (int i=0;i


Python3
# Python3 implementation of 
# the above approach
  
# Function to count the 
# total number of items
def items(n, a):
  
    # Sort the prices
    a.sort()
  
    # Choose the last element
    z = a[n-1]
  
    # Initial count of item
    x = 1
  
    # Sum to keep track of 
    # the total price 
    # of free items
    s = 0
    for i in range(0, n-1):
  
        s += a[i]
  
        # If total is less than 
        # or equal to z then 
        # we will add 1 to the answer
        if (s <= z):
            x+= 1
        else:
            break
    return x
  
n = 5
a = [5, 3, 1, 5, 6]
print(items(n, a))


C#
// C# implementation of the 
// above approach
using System;
  
class GFG
{
// Function to count the 
// total number of items 
static int items(int n, int []a)
{ 
  
    // Sort the prices 
    Array.Sort(a);
  
    // Choose the last element 
    int z = a[n - 1]; 
  
    // Initial count of item 
    int x = 1;
  
    // Sum to keep track of 
    // the total price 
    // of free items 
    int s = 0;
    for (int i = 0; i < n - 1; i++) 
    {
        s += a[i]; 
  
        // If total is less than or equal to z 
        // then we will add 1 to the answer 
        if (s <= z) 
            x += 1;
        else
            break;
    }
    return x;
}
  
// Driver code
static public void Main ()
{
    int n = 5;
    int []a = {5, 3, 1, 5, 6};
    Console.WriteLine(items(n, a)); 
}
}
  
// This code is contributed 
// by akt_mit


PHP


输出:
3