#include

using namespace std;

```
int main(){
int t,n,i,w[30],l[30],tw=0,tl=0;
cin>>t;
while(t--!=0){
cin>>n;
for(i=1;i<=n;i++){
scanf("%d",&w[i]);
}
for(i=1;i<=n;i++){
scanf("%d",&l[i]);
}
for(i=1;i<=n;i++){
tw=tw+w[i];
tl=tl+l[i];
}
if(tw<=tl)
cout<<n<<endl;
else
cout<<--n<<endl;
}
return 0;
```

}

First of all you are missing the header needed for handling scanf() in c++, add **cstdio**.

Secondly your indexing is wrong.

As the array sizes are thirty (30) so indexing starts from 0 upto 29, i.e., `for(i=0;i<n;i++)`

, but if indexing is to be started from 1 upto 30 than declare the array size as “31”.

Thirdly your solution is not correct. It is giving wrong answer for the second sample case.

Here is a link to your code on ideone modified by me, or you can check my AC solution here.

```
#include<cstdio> //for scanf(), printf()
#include<iostream>
#include<algorithm> //for sorting
using namespace std;
int main(){
int t,n,i,w[30],l[30],tw=0,tl=0;
int ans,j;
cin>>t;
while(t--!=0){
cin>>n;
/* as the array sizes are thirty (30) so indexing starts from 0 upto 29
i.e., for(i=0;i<n;i++)
but if indexing is to be started from 1 upto 30 than declare the array size as "31"
*/
for(i=0;i<n;i++){
scanf("%d",&w[i]);
}
for(i=0;i<n;i++){
scanf("%d",&l[i]);
}
/*
for(i=1;i<=n;i++){
tw=tw+w[i];
tl=tl+l[i];
}
if(tw<=tl)
cout<<n<<endl;
else
cout<<--n<<endl;
*/
// modified block
std::stable_sort(l,l+n); // you can use any sorting method
std::stable_sort(w,w+n); // as long as it sorts in non-decreasing order
ans=0;
for(i=0,j=0;i<n && j < n; i++) {
while(j < n && w[i]>l[j])
j++;
if (j<n) {
ans++;
j++;
}
}
cout<<ans<<endl;
}
return(0);
}
```

For more clarification, read the editorial here.

1 Like

Thanks a lot … You are awesome !!!

You’re welcome, happy to help.

Can you please tell me why have you sorted the elements in those arrays ?

Sorting is not necessary for this problem.You can take the pies one by one and solve it via greedy algorithm.

You can take it rack by rack, i.e., choose the first rack, see how many pies can be positioned on it and choose the one with the highest weight, and iterate over it.

But this will take more time compared to the sorted approach for large values of n ( more no. of racks and pies).