Bhavya

Code -> Break -> Fix -> Blog

Codility Problem : Find max deviation index

Leave a comment

Problem statement:

For a given array say [1,-5,8,3,-10,3,5,8] find the index which is far-most from the avg.

Answer : 4 i.e. -10 is far-most from the average i.e. 1.75.

Solution:


public static int solution3(double[] arr)
{
int max = 0;
int min = 0;
double avg = arr[0];

if (arr.Length == 0)
{
return -1;
}

for (int i = 0; i < arr.Length; i++)
{
if (arr[i] < arr[min])
{
min = i;
}

if (arr[i] > arr[max])
max = i;

avg += arr[i];
}

avg = avg / arr.Length;

var a1 = avg - arr[min];
var a2 = avg - arr[max];

if (Math.Abs(a1) > Math.Abs(a2))
{
return min;
}
else
{
return max;
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s