Skip to content

Instantly share code, notes, and snippets.

@nahiyan
Created December 7, 2019 08:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nahiyan/bc749a49fd657cb1f8c3670c22335bc7 to your computer and use it in GitHub Desktop.
Save nahiyan/bc749a49fd657cb1f8c3670c22335bc7 to your computer and use it in GitHub Desktop.
#include <stdio.h>
int main()
{
// Number of test cases
int n;
scanf("%d", &n);
// Minimum distances
int distances[n];
// Loop through test cases
int i;
for (i = 0; i < n; i++)
{
// Number of streets
int m;
scanf("%d", &m);
// Streets
int streets[m];
// Loop through streets
int j;
for (j = 0; j < m; j++)
{
scanf("%d", &streets[j]);
}
// Calculate median
int median;
if (m % 2 == 0)
{ // even
median = (streets[(m / 2) - 1] + streets[(m / 2)]) / 2;
}
else
{ // odd
median = streets[(m / 2)];
}
// Calculate distance from median and all the streets
distances[i] = 0; // initiate the distance with 0
for (j = 0; j < m; j++)
{
int distance = streets[j] - median;
if (distance < 0)
distances[i] += distance * -1;
else
distances[i] += distance;
}
}
// Display minimum distances of each test case
for (i = 0; i < n; i++)
{
printf("%d\n", distances[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment