TopCoder problem "MagicCube" used in SRM 256 (Division I Level One , Division II Level Two)

Problem Statement

    We've all seen magic squares before. They are square grids full of numbers arranged so that the rows, columns and diagonals all have the same sum:
 8 1 6
 3 5 7
 4 9 2
In the above figure, each row, column and diagonal sums to 15.

We'd like to extend the magic square to the magic cube. In a magic cube, we'll ignore the diagonals, but would like the rows, columns and pillars (pillars are analogous to rows and columns, but in the third dimension) to all have the same sum. You will be given 27 numbers that form the 27 values in a 3x3x3 cube. The number at (i,j,k) in the cube will be represented by element i*9 + j*3 + k of the input.

We can define the 'magic score' of a cube as the difference between the largest sum and the smallest sum (where the sums come from rows, columns, and pillars). Your task is to try to make the cube slightly more magical by trying to decrease its magic score. You should try to find two numbers in the cube that can be swapped to lower the cube's magic score. You should return the minimum possible magic score of the cube after you perform one swap. If there is no swap that would lower the magic score, return the magic score without any swaps.


Method signature:int getScore(int[] nums)
(be sure your method is public)


-nums will contain exactly 27 elements, each between 1 and 100, inclusive.


Returns: 0
Returns: 18
In the original cube, the magic score is 51-31=20. By swapping the numbers at (0,0,1) and (1,2,0), we can improve the magic score to 51-33=18
Returns: 17

Problem url:

Problem stats url:




PabloGilberto , brett1479 , Olexiy

Problem categories:

Simple Math