Maximum Number of Ones Problem
Description
LeetCode Problem 1183.
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
Solution
Approach: Count Repeating Positions, Pick the Best Ones
Let x = sideLength. The key observation is that the best matrix can be built from a single x * x tile repeated in both directions:
- Choose at most
maxOnespositions(r, c)inside one tile, with0 <= r, c < x. - Put a one at every cell
(i, j)withi % x == randj % x == c.
This is always valid: any x * x square in the matrix, wherever it sits, contains exactly one cell of each class (i % x, j % x), so it holds exactly as many ones as there are chosen positions. And it is optimal: one can show that no valid matrix has more ones than the best such tiling, so we only need to choose the positions well.
Position (r, c) appears rows * cols times in the matrix, where rows = (width - 1 - r) / x + 1 counts the values r, r + x, r + 2x, ... below width (and cols the same for height). Positions with a small r or c can appear one extra time when the size is not a multiple of x. So compute the count of all x * x positions, sort them in decreasing order and add up the largest maxOnes.
In Example 1, the four positions of a 2 * 2 tile appear 4, 2, 2 and 1 times in a 3 * 3 matrix: with maxOnes = 1 the answer is 4, with maxOnes = 2 it is 4 + 2 = 6.
Complexity: O(x2 log x) time for sorting the x2 counts, and O(x2) space.
class Solution:
def maximumNumberOfOnes(self, width: int, height: int, sideLength: int, maxOnes: int) -> int:
x = sideLength
# Cells (i, j) and (i + x, j), (i, j + x) are interchangeable: put a one at offset (r, c)
# of the x * x tile and it repeats at every (r + a*x, c + b*x) in the matrix.
copies = []
for r in range(x):
for c in range(x):
rows = (width - 1 - r) // x + 1 # how many of r, r + x, r + 2x, ... are < width
cols = (height - 1 - c) // x + 1
copies.append(rows * cols)
copies.sort(reverse=True)
return sum(copies[:maxOnes]) # use the offsets that repeat the most