Minimum Scalar Product

August 10, 2012

Today’s exercise comes to us from the practice round of Google Code Jam 2008.

You are given two vectors v1=(x1,x2,…,xn) and v2=(y1,y2,…,yn). The scalar product of these vectors is a single number, calculated as x1y1+x2y2+…+xnyn.

Suppose you are allowed to permute the coordinates of each vector as you wish. Choose two permutations such that the scalar product of your two new vectors is the smallest possible, and output that minimum scalar product.

Google gives two examples: the minimum scalar product of the two vectors (1 3 -5) and (-2 4 1) is -25, and the minimum scalar product of the two vectors (1 2 3 4 5) and (1 0 1 0 1) is 6.

Your task is to write a program that finds the minimum scalar product of two vectors. When you are finished, you are welcome to read or run a suggested solution, or to post your own solution or discuss the exercise in the comments below.

Is there a simple proof of the assertion that this always works? I looked briefly but failed to find one on the web and I need to attend to other things. I did find some other pages that simply assert that this pair of permutations produces the minimum. I found a purported counter-example that failed to be a counter-example. And I wrote a test program, below, that seems to confirm the assertion by always returning an empty set of permutations (of the second vector) that produce an even smaller result. So I believe it but if there is a memorable proof, I’d like to know.

It’s not a proof, but a simple observation is that the maximum scalar product is produced by multiplying the largest item from each vector, then the second largest, and so on; then the minimum scalar product is the opposite. I’ll ask at a couple of web sites I know.

[…] Another post from Programming Praxis, this time we’re to figure out what is the minimum scalar product of two vectors. Basically, you want to rearrange two given lists a1, a2, …, an and b1, b2, …, bn such that a1b1 + a2b2 + … + anbn is minimized. […]