I am trying to implement the solution for the problem "Max Min" in HackerRank. The solution runs for some test cases but for few test cases it pops out showing "Terminated due to Time Out"
Problem:
Given a list of \$N\$ integers, your task is to select \$K\$ integers from the list such that its unfairness is minimized.
Unfairness = Max{K integer Set} - Min{K integer Set}
where max denotes the largest integer among the elements of \$K\$, and min denotes the smallest integer among the elements of \$K\$.
Input Format
- The first line contains an integer \$N\$.
- The second line contains an integer \$K\$.
- \$N\$ lines follow. Each line contains an integer that belongs to the list \$N\$.
Note: Integers in the list \$N\$ may not be unique.
Output Format
An integer that denotes the minimum possible value of unfairness.
Constraints
- \$2 \le N \le 10^5\$
- \$2 \le K \le N\$
- \$0 \le \text{integer in} N \le 10^9\$
Sample Input #00
7 3 10 100 300 200 1000 20 30
Sample Output #00
20
Can anyone please point to me which part of my code is taking longer to implement and what a better solution can be?
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
#define MAX 100000
#define MAX_VAL 1000000001
int list[MAX];
int main() {
int N, K;
int i;
int unfairness=0;
scanf_s("%d %d", &N, &K);
int set = K - 1;
for (i = 0; i < N; i++)
scanf_s("%d", &list[i]);
for (int l = 0; l < N - 1; l++){
for (int j = 0; j < N - l - 1; j++)
{
if (list[j] > list[j + 1])
{
int temp;
temp = list[j];
list[j] = list[j + 1];
list[j + 1] = temp;
}
}
}
for (int x = 0; x < N - set; x++)
{
int differ = list[x + set] - list[x];
//printf("Dif - %d\n", differ);
//printf("Unfair - %d\n", unfairness);
if (unfairness == 0){
unfairness = differ;
}
else if (differ<unfairness)
unfairness = differ;
}
printf("%d", unfairness);
return 0;
}