Q:

Minimise the sum of difference between each element of an Array and an integer K

Given an Array A of N non negative integers, find an integer k, such that the sum of difference of each element with k is minimum.
i.e. Summation(abs(A[i] - k)), 1 <= i <= N, or simply
|A[1] - k| + |A[2] - k| + |A[3] - k| + ... + |A[N] - k|
My Approach:
low = minimumValueInArray(A);
high= maximumValueInArray(A);
ans = Infinite;
for (k = low; k <= high; k++) {
    temp = 0;
    for (i = 1; i <= N; i++) {
        temp += abs(A[i] - K);
    }
    ans = min(ans, temp);
}
return ans;

This is simply brute force approach trying to solve for all values of K.Can we optimise it.
What is the smarter way of doing this?
Reference: This was my logic behind this
Codejam Round 1B problem

A:

I get essentially the median.  To minimize the cost function, take the derivative.

To find the minimum of the cost function, find where the derivative is zero. The cost function is not continuously differentiable everywhere, but it is piecewise differentiable.  Let S = the sorted numbers of A and si be the ith largest number.
Case 1.  If m is odd
There will be floor(m/2) ai's less than the median and floor(m/2) ai's greater than the median. Selecting x = the median, gives -m/2 + 0 + m/2 = 0.

Case 2.  If m is even
The derivative will be zero for values in between si and s(i+1); i = m/2.  Then one can select any number k such that

Simple example
1 2 4 50
picking 2: 1 + 0 + 2 + 48 = 51
picking 4: 3 + 2 + 0 + 46 = 51
picking 3: 2 + 1 + 1 + 47 = 51
So arbitrarily pick s(m/2)
For a better algorithm, O(NlogN) you can sort the numbers and then pick (m+1)/2 or m/2 as appropriate from above or you can use the kth largest element which can compute the answer in O(N).

