Friday, 2 May 2014

Maximum items

You are given n items. For each i, item numbered i has a price (in rupees) whose value is stored in v[i]. Here v is the array of prices given as input.  A second input value referred to as MAX is also given, and it represents MAX rupees.  MAX is the maximum amount of money that can be spent.  Find the maximum number of items that can be bought with  MAX rupees.  This is what your program must compute.

Input
The first line will contain two inputs n and MAX.
Second line contains the array v, where elements of v are separated by spaces.

Output
Maximum number of items one can buy.


Explanation:  You can only buy items of values 2 and 4 which sums to 6. You cannot buy item of value 9 since it will exceed the amount you can spend.




#include<stdio.h>
#include<stdlib.h>

int comp (const void * elem1, const void * elem2) 
{
int f = *((int*)elem1);
int s = *((int*)elem2);
if (f > s) return  1;
if (f < s) return -1;
return 0;
}
int getMaxItems(int arr[],int n,int MAX)
{
  int x,i,j,count=0;
  for(i = 0; i < n; i++)   
  {
   for(j = i + 1; j < n; j++)  
   {  
     if((arr[i])>(arr[j]))
      {  
       x=arr[j];  
       arr[j]=arr[i];
       arr[i]=x;
      }
   }
  }
  x=0;
  for(i=0;i<n;i++)
  {
   if(x<MAX)
    {
    x=x+arr[i];
    count++;
     }
   if(x>MAX)
  {
    x=x-arr[i];
    count--;
     }
  }
  return count;
}
int main()
{
int n,*arr,MAX,i=0;
scanf("%d",&n);
scanf("%d",&MAX);
arr  = (int*)malloc(sizeof(int)*n);
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
printf("%d",getMaxItems(arr,n,MAX));
return 0;
}

No comments: