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).