I'm doing a code-challenge problem:
Input
The first line consists of an integer T
(T ≤ 100) which represents the number of test cases. Each test case consists of an integer N
(5 ≤ N ≤ 100.000) which represents the number of integers, followed by a line that consists of N
integers Ai
(0 ≤ Ai ≤ 1000) separated by a space.
Output
For each test case, print in a line an integer that represents the sum of 5 largest numbers.
My code (below) works for small tests, but on the online judge, it resulted in Time Limit Exceeded. Some approaches I've tried that I think speed up the program (need confirmation):
- Changing language from C++ to C (does it give significant boost?)
- When calculating the sum, I use
while
instead offor
loop (which one is more effective?)
#include <stdio.h>
int main () {
int testCases;
scanf("%d", &testCases);
for (int i = 1; i <= testCases; i++) {
int size, sum, temp, k, limit;
sum = 0;
temp = 0;
scanf("%d", &size);
int array[size];
for (int i = 0; i < size; i++) {
scanf("%d", &array[i]);
}
for (int i = 0; i < size; i++) {
for (int j = i+1; j < size; j++) {
if (array[j] < array[i]) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
} else {
continue;
}
}
}
k = size - 1;
limit = size - 6;
while (k > limit) {
sum += array[k];
k--;
}
printf("%d\n", sum);
}
}