Header Ad

HackerEarth In search of Samosa problem solution

In this HackerEarth In search of Samosa problem solution, Shiro is an avid lover of Samosas. He went down to the Samosa street to have some. But he only has K units of money with him. There are N shops on the street and unfortunately, all of them have only one samosa remaining. You are also given an array A[ ] , where Ai is the cost of a samosa on the i'th shop.
Find the maximum samosas that Shiro can eat.


HackerEarth In search of Samosa problem solution


HackerEarth In search of Samosa problem solution.

#include<bits/stdc++.h>


using namespace std;

#define rep(i,n) for(i=0;i<n;i++)
#define ll long long
#define elif else if
#define pii pair<int,int>
#define mp make_pair
#define pb push_back
#define CLEAR(array, value) memset(ptr, value, sizeof(array));
#define si(a) scanf("%d", &a)
#define sl(a) scanf("%lld", &a)
#define pi(a) printf("%d", a)
#define pl(a) printf("%lld", a)
#define pn printf("\n")

int main()
{
freopen("int","r",stdin);
freopen("out","w",stdout);
ios::sync_with_stdio(false);
int n,i,j,k;
cin>>n>>k;
assert(1<=n && n<=1000);
assert(0<=k && k<=1000);
vector<int>v(n);
rep(i,n){
cin>>v[i];
assert(1<=v[i]<=1000);
}
sort(v.begin(),v.end());
j=0;
rep(i,n)
{
k-=v[i];
if(k>=0)
j++;
else
break;
}
cout<<j<<"\n";
return 0;
}

Second solution

#include<bits/stdc++.h>
using namespace std;
int main(){

int N,K;
cin>>N>>K;
assert(N>=1&&N <= 1000);
assert(K>=0&&K <= 1000);
vector<int>A(N),cum(N);
for(int i=0;i<N;i++){
cin>>A[i];
assert(A[i]>=0&&A[i]<= 100);
}
sort(A.begin(),A.end());
cum[0]=A[0];
for(int i=1;i<N;i++)
cum[i]=cum[i-1]+A[i];
int count=0;
for(count=0;count<N;count++){
if(cum[count]<=K)
continue;
else
break;
}
cout<<count<<endl;
}

Post a Comment

0 Comments