This problem asks to find the maximum number of ones that can be placed in a matrix of size width x height
such that any square submatrix of size sideLength x sideLength
contains at most maxOnes
ones. The solution uses a clever observation about equivalent positions within the matrix.
Core Idea:
The key insight is that positions within the matrix that are equivalent modulo sideLength
contribute equally to the number of ones in any sideLength x sideLength
square submatrix.
Let's illustrate with an example: width = 5
, height = 4
, sideLength = 2
, maxOnes = 2
.
Consider a 2 x 2
submatrix. If we place a '1' at (0, 0), it's equivalent to placing a '1' at (0, 2), (2, 0), (2, 2), (4, 0), (4, 2), and so on. Similarly, (0, 1) is equivalent to (0, 3), (2, 1), (2, 3), (4, 1), (4, 3), etc. (1, 0) is equivalent to (1, 2), (3, 0), (3, 2), and (1, 1) to (1, 3), (3, 1), (3, 3).
Therefore, we only need to count the number of occurrences of each of these equivalent positions and determine how many ones can be placed in these positions while satisfying the maxOnes
constraint per sideLength x sideLength
submatrix.
Algorithm:
Count Equivalent Positions: Create an array cnt
of size sideLength * sideLength
. Iterate through each cell (i, j)
of the matrix. The index k = (i % sideLength) * sideLength + (j % sideLength)
represents the equivalent position. Increment cnt[k]
to count the number of occurrences of this equivalent position.
Sort and Sum: Sort cnt
in descending order. The top maxOnes
elements represent the equivalent positions that contribute the most ones to the matrix. Sum these top maxOnes
elements to get the maximum number of ones.
Time and Space Complexity:
Time Complexity: O(width * height + sideLength² * log(sideLength²)). The dominant factor is iterating through the matrix (O(width * height)) and sorting the cnt
array (O(sideLength² * log(sideLength²))). Since sideLength
is much smaller than width
and height
in most cases, the overall complexity is effectively O(width * height).
Space Complexity: O(sideLength²). The cnt
array is the primary space used, with size sideLength * sideLength
.
Code Examples (Python, Java, C++, Go, Javascript):
The code examples provided in the original response accurately implement this algorithm in several programming languages. They follow the steps outlined above: counting equivalent positions, sorting the counts, and summing the top maxOnes
counts to get the final result. The time and space complexities as described above apply to all of these implementations.