NewThe Learning module is now liveSee what's new

You are given an integer matrix matrix of size m × n and a positive integer frameSize.

For every frameSize × frameSize square submatrix, look only at its outer border, called its frame. The frame includes the top row, bottom row, left column, and right column of the square. Cells strictly inside the square are ignored. When frameSize = 1, the single cell is the frame. See the frames for some values of frameSize below for better understanding.

For each square, compute the sum of the numbers on its frame. Among all squares, find the maximum frame sum. Then look at every square whose frame sum equals this maximum, collect all distinct numbers that appear on those frames, and return the sum of those distinct numbers. Each number is counted only once, even if it appears multiple times or in multiple maximum-sum frames.

Constraints:

  • 1 ≤ m ≤ 100 (m = matrix.length)
  • 1 ≤ n ≤ 100 (n = matrix[0].length)
  • -104 ≤ matrix[i][j] ≤ 104
  • 1 ≤ frameSize ≤ min(m, n)

Example 1:

Input: 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]],        frameSize = 3 Output: 92 Explanation: With frameSize = 3, there are 9 possible 3 × 3 squares. The maximum frame sum is 54, achieved by the squares rooted (top-left corner) at (0, 0), (2, 0), and (2, 2).

  • The distinct values appearing on at least one of these frames are: {1, 3, 4, 5, 6, 7, 8, 9, 10, 18, 21}
  • Their sum is: 1 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 18 + 21 = 92. So the answer is 92.

Example 2:

Input: matrix = [[5,5,5,0,9,1,5],                  [5,0,5,0,5,0,5],                  [5,5,5,0,5,5,5]],        frameSize = 3 Output: 15

Example 3:

Input: matrix = [[10,-5,10],                  [-5,0,-5],                  [10,-5,10]],        frameSize = 3 Output: 5


Accepted
10/75
Acceptance Rate13.3%
Test Cases
Input
matrix =
frameSize =
Output
Expected