Google Code Jam - Minimum Scalar Product
With the Google Code Jam 2011 less than four weeks away, it is time for some finger exercises.
Let's start with the Minimum Scalar Product, which should only take you a few minutes.
Here's the Java version, which will only work for the small input set. I'll explain later.
- public static int getMinimumScalarProduct2(int[] x, int[] y) {
- Arrays.sort(x);
- Arrays.sort(y);
- int sum=0;
- for (int i = 0; i < x.length; i++) {
- sum += x[i] * y[x.length -1 -i];
- }
- return sum;
- }
What we do is sort both arrays, then multiply them. One starting from the beginning, the other from the end. So our biggest numbers are multiplied with the smallest. The math is on Google's solution page, we're just looking at coding here.
This works for the small input set, but not the large one. Why?
Take a look at the Limits:
Large dataset
T = 10
100 ≤ n ≤ 800
-100000 ≤ xi, yi ≤ 100000
The result of the large dataset will not fit in an int. So we switch to BigInteger, which can hold our results.
- public static BigInteger getMinimumScalarProduct(int[] x, int[] y) {
- Arrays.sort(x);
- Arrays.sort(y);
- BigInteger sum = BigInteger.ZERO;
- for (int i = 0; i < x.length; i++) {
- sum = sum.add( new BigInteger(""+ x[i]).multiply(new BigInteger(""+y[x.length -1 -i])));
- }
- return sum;
- }
Take a look in the BigInteger API doc, I'm very sure you'll need it for this years jam. I initially made the mistake of not assigning the result of sum.add() to sum.
Now, as I try to do a bit python, I will also present my python solution. Maybe Christian can spot my classic java thinking and provide a more python like version for my lines.
- f = open('../resources/codejam/msp-large.in', 'r')
- cases = int(f.readline())
- for i in range (0, cases):
- nrOfIntegers = f.readline()
- xs = f.readline()
- ys = f.readline()
- x = [int(s) for s in xs.split()]
- y = [int(s) for s in ys.split()]
- x.sort()
- y.sort()
- sum = 0
- size = len(x)
- for j in range(0, size):
- sum+= int(x[j])* int(y[size -1 - j])
- print sum
It's the exact same idea, so no suprises here.
Happy practicing.
- Login to post comments
Comments
Christian Harms - Mon, 04/11/2011 - 09:38
Ok, my python solution looks shorter, but the algorithm is not changed:
FrankieTheCoin (not verified) - Thu, 04/14/2011 - 19:25
I've done it some time ago and I believe that my algorithm is the same. Still python sorry. Going to learn Lua.
jhe (not verified) - Thu, 05/05/2011 - 13:33
N00bs! :Þ
Ismael (not verified) - Sat, 03/31/2012 - 10:44
Why this prodvides an incorrect ouput for me ?
Christian (not verified) - Mon, 04/02/2012 - 12:52
I guess you sorted the list of strings instead of integers?
Ismael (not verified) - Mon, 04/02/2012 - 14:07
OOOHHH Thx a lot!