TITLE: Choose integers so that average is close to given real number
QUESTION [6 upvotes]: I have a list of integers (that are consecutive). I also have a given real value that is between the min and max of the integers. I want to choose any number of integers from the given list, so that the mean of these integers is optimally close to the given real value. (alternatively, choose any number of integers so that the mean is within $\epsilon $ of the given value).
I don't know if this is a well posed problem or if it's even possible to solve/approximate. Any ideas and suggestions of how to approach this problem and even naive solutions are welcome.

REPLY [2 votes]: Here's an efficient way: find which fraction of the form $k/l$ (for integer values, and $l <= n$) is closet to your target. All the averages you can get will be of this format. Then observe that for a given $l$, you can get all the consecutive values of $k/l$ in a range. 
Example: By picking from $\{1,2,3,4\}$ you can reach:
$l=1: 1,2,3,4$
$l=2: 1.5, 2, 2.5, 3, 3.5$
$l=3: 2, 2.33, 2.66, 3 $
The range you can reach for $k/l$ is from the average of the first $l$ integers to the average of the last $l$ ones.
Enumerating the range is in the order of $n$ operations, finding the closest one is constant time, so you get an efficient algorithm for reasonable $n$ (millions or less).
I've implemented a rough prototype (C++, someone can probably translate it to Mathematica). See 
http://pastebin.com/91kXULTQ
Example output:
target is 3.14159
Average of 
-100, -99, -98, -97, -96, -95, -94, -93, -92, -91, -90, -89, -88, -87, -86, -85, -84, -83, -82, -81, -80, -79, -78, -77, -76, -75, -74, -73, -72, -71, -70, -69, -68, -67, -66, -65, -64, -63, -62, -61, -60, -59, -58, -57, -56, -55, -54, -53, -52, -51, -50, -29, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 
 is 3.14159

Quite interesting question. 
P.S.: The prototype has precision issues but the algorithm is there.