We want to find the smallest of that sum[(x-mu)^2] over all subsets of size k. That sum will be smallest when all k evaluations are close to each other. To get them all close to their neighbors, start by sorting the evaluations. If you remember your statistics, or if you do a little algebra, you'll see that sum[(x-mu)^2] = sum[x^2] - (sum[x]^2)/k So now it's easy to compute the Badness over the first k evaluations in the sorted list. Compute sx = sum[x], sxx = sum[x^2], and use that formula: Badness = sxx - sx*sx/k To move forward, we just need to add the next element to the end of the list, remove the first element in the list, and adjust sx and sxx. But that's easy: sx += newx - oldx sxx += newx*newx - oldx*oldx NewBadness = sxx - sx*sx/k Then, just check if NewBadness is better. Here is some python code: n, k = [int(x.strip()) for x in input().strip().split()] evals = [] for _ in range(n): evals.append( int(input().strip()) ) evals.sort() sx = 0.0 sxx = 0.0 for i in range(k): x = evals[i] sx += x sxx += x*x badness = sxx - sx*sx/k for i in range(k,n): oldx = evals[i-k] newx = evals[i] sx += newx-oldx sxx += newx*newx - oldx*oldx new_badness = sxx - sx*sx/k if new_badness