Problem Summary
Suppose there are K packets with (x1, x2, x3,….xk) candies in them, where xi denotes the number of candies in the ith packet, then we define unfairness as
Given N packets, find the minimum unfairness when you pick K out of N packets.
Solution
Obviously, we only need to consider the cases that K packets with the “closest” values, so we sort the array first.
Then let f[i] be the unfairness when we choose x[i],x[i+1],…,x[i+K-1].
In order to reduce time complexity, we need to find out the recurrence relation between f[i] and f[i+1].
f[i] = |x[i+K-1] - x[i+K-2]| + |x[i+K-1] - x[i+K-3]| + … + |x[i+K-1] - x[i]|
+ |x[i+K-2] - x[i+K-3]| + |x[i+K-2] - x[i+K-4]| + … + |x[i+K-2] - x[i]|
+ …
+ |x[i+1] - x[i]|
So, f[i+1] = f[i] + (K-1) × (x[i+K] + x[i]) - 2 × (x[i+1] + x[i+2] + … + x[i+K-1]).
The answer is the minimum of f[i] (1 ≤ i ≤ N-K+1).
Code
|
|