Assume the input is specified as an array of building objects, where each building has a number of residents an its distance from the start of the street.
Total distance = SUM(distance[i] * #residents[i])
I found here two questions that are similar but they have slightly different requirements:
Minimizing weighted sum: The solution of this question finds the minimum path crossing all points. Here I am looking for minimal sum of total distances from each building to the place where the mailbox is.
Minimum Total Distance From Locations: It uses 2D coordinates, and more important, the solution doesn't consider the weight (number of residents) on each location.
I saw this problem while reading Elements of Programming Interviews (really nice book, BTW), and this is listed as a variant of the quickselect algorithm. Considering that the median is the point that minimizes the sum of the distances, it looks like the solution would involve the quick selection to find the building at the "median" position of the street in O(N).
But I can't figure out how to account the residents on each building and still keep the solution linear.