Given a rectangular matrix matrix and an integer frameSize, consider the outer frames of all frameSize × frameSize contiguous square submatrices of matrix. Your task is the following:
• Calculate the sum of all numbers located on the frame of each frameSize × frameSize submatrix.
• Determine the maximum of all these sums.
• Considering only these frames with the maximum sum, find all the distinct numbers that appear in at least one of the frames. Each integer from these square frames should be calculated only once.
• Return the sum of these distinct numbers.
Note: A frameSize × frameSize square frame contains max(1, 4 × (frameSize - 1)) cells. See example for better understanding.
Note: You are not expected to provide the most optimal solution, but a solution with time complexity not worse than O(matrix.length^2 × matrix[0].length^2) will fit within the execution time limit.
Example:
For matrix = [[9, 7, 8, 9, 2], [6, 9, 9, 6, 1], [4, 10, 1, 3, 10], [18, 2, 3, 9, 3], [4, 6, 8, 5, 21]] and frameSize = 3, the output should be solution(matrix, frameSize) = 92.
If we consider all the 3 × 3 square frames in matrix, there are only 3 of them with a maximum sum of 54:
[[9, 7, 8], [6, 9, 9], [4, 10, 1]] (9 + 7 + 8 + 6 + 9 + 4 + 10 + 1 = 54)
[[4, 10, 1], [18, 2, 3], [4, 6, 8]] (4 + 10 + 1 + 18 + 3 + 4 + 6 + 8 = 54)
[[1, 3, 10], [3, 9, 3], [8, 5, 21]] (1 + 3 + 10 + 3 + 9 + 3 + 8 + 5 + 21 = 54)
The only distinct numbers are 1, 3, 4, 5, 6, 7, 8, 9, 10, 18, and 21. So the answer is 1 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 18 + 21 = 92.
Input/Output:
• [input] array.array.integer matrix: A rectangular matrix of integers. Guaranteed constraints: 1 <= matrix.length ≤ 50, 1 <= matrix[i].length ≤ 50, 0 <= matrix[i][j] <= 50.
• [input] integer frameSize: An integer representing the size of the square frames. Guaranteed constraints: 1 ≤ frameSize ≤ min(matrix.length, matrix[i].length).
• [output] integer: The sum of all distinct integers within any of the frameSize × frameSize square frames with the maximal sum.