Want Help Cracking FAANG?

(Then click this)

×
Back to Question Bank

1183. Maximum Number of Ones - Leetcode Solution

Code Implementation

class Solution:
    def maximumNumberOfOnes(self, width: int, height: int, sideLength: int, maxOnes: int) -> int:
        from collections import Counter
        freq = Counter()
        for i in range(sideLength):
            for j in range(sideLength):
                # Count how many times each position in the sideLength x sideLength block appears
                freq[(i, j)] = ((height - i + sideLength - 1) // sideLength) * ((width - j + sideLength - 1) // sideLength)
        # Take the maxOnes positions with the largest frequency
        return sum(cnt for _, cnt in sorted(freq.items(), key=lambda x: -x[1])[:maxOnes])
      
class Solution {
public:
    int maximumNumberOfOnes(int width, int height, int sideLength, int maxOnes) {
        vector<int> freq;
        for (int i = 0; i < sideLength; ++i) {
            for (int j = 0; j < sideLength; ++j) {
                int count = ((height - i + sideLength - 1) / sideLength) * ((width - j + sideLength - 1) / sideLength);
                freq.push_back(count);
            }
        }
        sort(freq.begin(), freq.end(), greater<int>());
        int res = 0;
        for (int i = 0; i < maxOnes; ++i) {
            res += freq[i];
        }
        return res;
    }
};
      
class Solution {
    public int maximumNumberOfOnes(int width, int height, int sideLength, int maxOnes) {
        List<Integer> freq = new ArrayList<>();
        for (int i = 0; i < sideLength; i++) {
            for (int j = 0; j < sideLength; j++) {
                int count = ((height - i + sideLength - 1) / sideLength) * ((width - j + sideLength - 1) / sideLength);
                freq.add(count);
            }
        }
        Collections.sort(freq, Collections.reverseOrder());
        int res = 0;
        for (int i = 0; i < maxOnes; i++) {
            res += freq.get(i);
        }
        return res;
    }
}
      
var maximumNumberOfOnes = function(width, height, sideLength, maxOnes) {
    let freq = [];
    for (let i = 0; i < sideLength; i++) {
        for (let j = 0; j < sideLength; j++) {
            let count = Math.floor((height - i + sideLength - 1) / sideLength) * Math.floor((width - j + sideLength - 1) / sideLength);
            freq.push(count);
        }
    }
    freq.sort((a, b) => b - a);
    let res = 0;
    for (let i = 0; i < maxOnes; i++) {
        res += freq[i];
    }
    return res;
};
      

Problem Description

You are given four integers: width, height, sideLength, and maxOnes. Your task is to construct a height x width binary matrix (filled with 0s and 1s) such that:
  • For every sideLength x sideLength sub-square of the matrix, there are at most maxOnes ones in that square.
Your goal is to maximize the total number of ones in the entire matrix.
Constraints:
  • Each sideLength x sideLength sub-square must have at most maxOnes ones.
  • Each cell can be either 0 or 1.
  • You must maximize the total number of ones in the whole matrix.

Thought Process

At first glance, you might consider brute-forcing all possible placements of ones in the matrix, checking each time if the sideLength x sideLength constraint is satisfied. However, this approach is infeasible for large matrices due to the exponential number of possibilities. Upon closer inspection, you can notice a repeating pattern: every sideLength x sideLength block overlaps in a regular, tiled fashion. Thus, the problem is about optimally distributing ones within a single sideLength x sideLength block and replicating this pattern across the entire matrix. The key is to place ones in the most "frequent" positions within the block — the positions that appear most often in the overall matrix. By prioritizing these, you maximize the total number of ones.

Solution Approach

The solution leverages the repeating structure of sideLength x sideLength blocks:
  1. Block Decomposition:
    • Divide the matrix into sideLength x sideLength blocks. The pattern in each block will repeat throughout the matrix.
  2. Frequency Calculation:
    • For each position (i, j) in the block, calculate how many times it will appear in the overall matrix. This is determined by how many times the block "fits" across the width and height.
  3. Greedy Placement:
    • Sort all positions in the block by their frequency (i.e., how many times they appear in the matrix).
    • Select the maxOnes most frequent positions and set them to 1 in the block pattern.
  4. Total Ones Calculation:
    • The total number of ones in the matrix is the sum of frequencies of these selected positions.
This approach ensures the global maximum while always respecting the maxOnes constraint for every block.

Example Walkthrough

Example:
Suppose width = 3, height = 3, sideLength = 2, maxOnes = 2.
  • The block is 2x2. There are 4 positions: (0,0), (0,1), (1,0), (1,1).
  • For each position, calculate how many times it appears in the 3x3 matrix:
    • (0,0): appears in all 4 possible 2x2 sub-squares (top-left, top-right, bottom-left, bottom-right) → frequency = 4
    • Other positions also appear 4 times each.
  • All positions have the same frequency. We can pick any 2 positions (since maxOnes = 2).
  • Total ones = 4 (frequency) * 2 (positions) = 8.
Step-by-step:
  1. Calculate frequencies for each block position.
  2. Pick the top 2 positions.
  3. Sum their frequencies for the answer.

Time and Space Complexity

  • Brute-force Approach:
    • Would require checking all possible assignments of ones and zeros, which is exponential in the number of cells — O(2^{width \times height}).
  • Optimized Approach (as above):
    • We only consider the sideLength x sideLength block, which is at most 400 positions (if sideLength=20).
    • For each block position, we compute its frequency in O(1).
    • Sorting the frequencies takes O(sideLength^2 \log sideLength^2).
    • Overall time complexity: O(sideLength^2 \log sideLength^2).
    • Space complexity: O(sideLength^2) for storing frequencies.

Summary

To maximize the number of ones in a matrix under the given constraints, we exploit the repeating block structure. By calculating the frequency of each position's appearance and greedily selecting the most frequent ones (up to maxOnes), we achieve the optimal solution efficiently. This approach elegantly reduces a seemingly complex problem to a manageable, pattern-based calculation.