-2

This problem was asked on ACM ICPC 2018 preliminary round. You have to print any array of length N whose standard deviation is K.

  • Hint: Given an array with K elements, it's possible to extend it to arbitrary length by adding elements with a specific value such that nor the mean nor the variance change. – Margaret Bloom Nov 06 '17 at 07:55

1 Answers1

0

You don't mention constraints on data types, so I assume you are OK with floating-point results (the alternative is that you want integer-only solutions, and if that is the intent then the below is woefully inadequate to that task.)

Over the reals, we expect that given an array of length n-1 with standard deviation k', we should be able to derive an array of length n with standard deviation k > k' by adding some element to the shorter array. That is, by adjusting the new element, we can sweep continuously over all values starting at k and going on up.

With this observation, we might guess we can start with any nominal array - say, [0, 0, ..., 0] of length n - 1, and add some element to it to make the standard deviation "come out" right. Let's call the value to be added v. The mean of such an array would be:

m = (0 + 0 + ... + 0 + v) / n = v/n

The variance would be:

s^2 = [(0-m)^2 + (0-m)^2 + ... + (0-m)^2 + (v-m)^2] / n

We can substitute in the expression for the mean:

s^2 = [(v/n)^2 + (v/n)^2 + ... + (v/n)^2 + (v-v/n)^2] / n

We can factor out a v^2 term:

s^2 = v^2[(1/n)^2 + ... + (1/n)^2 + (1-1/n)^2] / n

We can replace the repeated addition with multiplication:

s^2 = v^2 [(n-1)(1/n)^2 + (1-1/n)^2] / n

Finally, we can solve for v to see what we add to our array:

v = s / sqrt([(n-1)(1/n)^2 + (1-1/n)^2] / n)

Some algebra shows this simplifies to:

v = s * n / sqrt(n - 1)

Recall we are given s = k, so by substituting in we can determine v:

v = k * n / sqrt(n - 1)

The resulting array will contain n - 1 zeroes and one v.

Example: k = 1, n = 10:

v = 1 * 10 / sqrt(9) = 10/3
m = 1/3
s = sqrt((9*(1/3)^2 + (10/3-1/3)^2)/10)
  = sqrt((9(1/9) + (9/3)^2)/10)
  = sqrt((1 + 9)/10)
  = sqrt(10/10) = 1
Patrick87
  • 27,682
  • 3
  • 38
  • 73