How can I find pairs of numbers in a matrix without using so many nested loops?
You may check if the algorithm outlined below are fast enough.
Sort the numbers in the 3D array that are in the given range and keep track of the indexes.
Now do a nested loop where the outer loop find candidates for the smallest number and the inner for the largest. The inner loop starts with the next number in the list and terminates as soon as you find numbers that correspond to none-overlapping sub-fields (first number that satisfy condition 2, all remaining numbers fails condition 3) or the difference are greater than the best pair of numbers already found (this and all remaining numbers fails condition 3). Update the information for the best candidate pair if appropriate when the inner loop terminates.
I have to write an algorithm that will find two numbers in a 3D array (nested lists) that are: 

That are in a given range (min < num1, num2, < max)
Do not overlap  
Are as close in value as possible ( abs(num1 - num1) is
minimal)
If there exists more pairs of numbers that satisfy 1),
2) and 3), pick the ones whose sum is maximal

Original data is a N x N field consisting of elementary squares that each have a single random number in them. The problem is to find two sub-fields whose sums satisfy the 4 conditions written. I calculate all possible sums and store them in the 3D array sums[i][j][k] with coordinates of starting point (i, j) and its size (k). I need to keep track of indexes to ensure that fields do not overlap.
Right now I am doing this using 6 nested for loops (one for each index, 3 indexes per number) and lots of if statements (to check that sums are in range and fields do not overlap) and then simply iterating over every possible combination which is really slow.
Is there a faster way to do it (maybe without so many loops)? Only standard libraries are allowed