I was solving the lunch boxes problem on HackerEarth but as I submitted my solution most of the test cases were passed and the rest showed 'Time Limit Exceeded'. I would be very grateful if you could help me improve the algorithm of my code to reduce the runtime.
Following is the Problem
Alice works as a restaurant manager. The restaurant has prepared 'N' lunch boxes and Alice plans to distribute them to some schools. Consider that there are 'M' schools and an \$i^{th}\$ school orders \$A_i\$ lunch boxes.
She wants to distribute lunch boxes to as many schools as possible. Also, she has the following rule:
For an \$i^{th}\$ school, she gives either zero or \$A_i\$ lunch boxes
Your task is to help Alice to determine the maximum number of schools that can get lunch boxes.
Input format
- The first contains an integer \$t\$ that denotes the number of test cases in the input.
- Each test case consists of two lines:
- The first line contains two integers \$N\$ and \$M\$.
- The second line contains integers \$A_1, A_2, ..., A_m\$.
Constraints
- \$ 1 \le t \le 10 \$
- \$ 1 \le N, M \le 10^5 \$
- \$ 1 \le A_i \le 10^6 \$
My code
#include<stdio.h>
int main()
{
int t;
scanf("%d", &t);
while(t--){
int n,m;
scanf("%d", &n);
scanf("%d", &m);
int a[m];
for(int i=0; i<m; i++){
scanf("%d", &a[i]);
}
for(int i=0; i<m; i++){
for(int j=i + 1; j<m; j++){
if(a[i] > a[j]){
int temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
int sum=0, count=0;
for(int i=0; i<m; i++){
sum=sum+a[i];
if(sum>n){
break;
}
else if(sum<=n)
count++;
}
printf("%d\n", count);
}
}