I am stuck in clearing all the test cases for a simple algorithm and I am looking for the reasons or the modifications that I should be doing in my code. Here , there is an inline link to the question.
The probable solution can be sorting the two arrays and then adding the corresponding terms but it does not complete all the test cases.
#include <stdio.h>
#include <assert.h>
int main() {
long long n, i;
scanf("%lld", &n);
if (!(n >= 1 && n <= 1000000))
exit(1);
long long s[n], c[n], sum = 0, temp = 0, j;
// taking input for cat and strength array
for (i = 0; i < n; i++) {
scanf("%lld", &s[i]);
if (!(s[i] >= 1 && s[i] <= 1000000))
exit(1);
}
for (i = 0; i < n; i++) {
scanf("%lld", &c[i]);
if (!(c[i] >= 1 && c[i] <= 1000000))
exit(1);
}
// Sorting the C array
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (c[i] > c[j]) {
temp = c[i];
c[i] = c[j];
c[j] = temp;
}
}
}
// sorting the S array
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (s[i] > s[j]) {
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
// Finally adding up the sorted elements
for (i = 0; i < n; i++) {
sum = sum + (s[i] * c[i]);
}
printf("%d ", sum);
getch();
}
c[i], s[i] <= 1e6
you can even sort the arrays in linear time. Wrong answers
, replace printf("%d ",sum);
with printf("%lld ",sum);
sum is a variable of long long type Note that n <= 10^6
. Your algorithm has O(n^2)
time complexity. It is too slow. You definitely need to use more efficient sorting algorithm. For example, you can use qsort
from stdlib.h
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.