1183. Maximum Number of Ones π
SourceBiweekly Contest 8 Q4DifficultyHardRating2366
Description
Consider a matrix M with dimensions width * height, such that every cell has value 0 or 1, and any square sub-matrix of M of size sideLength * sideLength has at most maxOnes ones.
Return the maximum possible number of ones that the matrix M can have.
Example 1:
Input: width = 3, height = 3, sideLength = 2, maxOnes = 1 Output: 4 Explanation: In a 3*3 matrix, no 2*2 sub-matrix can have more than 1 one. The best solution that has 4 ones is: [1,0,1] [0,0,0] [1,0,1]
Example 2:
Input: width = 3, height = 3, sideLength = 2, maxOnes = 2 Output: 6 Explanation: [1,0,1] [1,0,1] [1,0,1]
Constraints:
1 <= width, height <= 1001 <= sideLength <= width, height0 <= maxOnes <= sideLength * sideLength
Solutions
Solution 1: Count Equivalent Positions
Thinking
The matrix tiles a \(\textit{sideLength}\times \textit{sideLength}\) motif that holds at most \(\textit{maxOnes}\) ones. Cell \((i,j)\) is tied to \((i\bmod x,j\bmod x)\); that residual's frequency is the payoff of placing a one there. Count the \(x^2\) residuals and sum the largest \(\textit{maxOnes}\).
For convenience, let's denote \(x = \textit{sideLength}\).
Consider a \(x \times x\) square, we need to select at most \(\textit{maxOnes}\) points inside the square and set them to 1. Note that when the point at coordinate \((i, j)\) is selected, all points at coordinates \((i\pm k_1 \times x, j\pm k_2 \times x)\) can be equivalently set to 1. Therefore, we calculate the number of equivalent positions of the coordinate \((i, j)\) in the matrix, and select the top \(\textit{maxOnes}\) with the most quantities.
The time complexity is \(O(mn)\), where \(m\) and \(n\) are the number of rows and columns of the matrix, respectively.
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |