Maximum Number of Ones - Problem

Consider a matrix M with dimensions width × height, where every cell has value 0 or 1. There is a constraint that any square sub-matrix of M of size sideLength × sideLength can have at most maxOnes ones.

Goal: Return the maximum possible number of ones that the matrix M can have while satisfying this constraint.

Key insight: This is a mathematical optimization problem where we need to distribute ones optimally across the matrix such that no square sub-matrix violates the constraint.

Input & Output

Example 1 — Basic Square
$ Input: width = 3, height = 3, sideLength = 2, maxOnes = 1
Output: 4
💡 Note: In a 3×3 matrix, we need every 2×2 sub-matrix to have ≤1 ones. Optimal placement is checkerboard pattern in corners: positions (0,0), (0,2), (2,0), (2,2) can all be 1 without violating constraints.
Example 2 — Rectangular Matrix
$ Input: width = 2, height = 3, sideLength = 2, maxOnes = 1
Output: 2
💡 Note: In a 2×3 matrix with 2×2 constraint, we have two 2×2 sub-matrices that overlap. We can place at most 2 ones total while keeping each sub-matrix ≤1.
Example 3 — No Ones Allowed
$ Input: width = 3, height = 3, sideLength = 2, maxOnes = 0
Output: 0
💡 Note: When maxOnes = 0, no sub-matrix can contain any ones, so the entire matrix must be all zeros.

Constraints

  • 1 ≤ width, height ≤ 109
  • 1 ≤ sideLength ≤ min(width, height)
  • 0 ≤ maxOnes ≤ sideLength2

Visualization

Tap to expand
Maximum Number of Ones INPUT Matrix M (3x3) ? ? ? ? ? ? ? ? ? 2x2 window (sideLength=2) width = 3 height = 3 sideLength = 2 maxOnes = 1 Max 1 one per 2x2 window Maximize total ones in M ALGORITHM STEPS 1 Count Position Frequency Count how many times each position (i%s, j%s) appears 2 Build Frequency Map For 2x2 template positions: 4 2 2 1 freq 3 Sort Descending Sort frequencies: [4,2,2,1] Pick top maxOnes positions 4 Sum Top Frequencies maxOnes=1, so pick top 1 Result = 4 (highest freq) ceil(w/s) * ceil(h/s) = ceil(3/2) * ceil(3/2) = 4 FINAL RESULT Optimal Matrix Configuration 1 0 1 0 0 0 1 0 1 All 2x2 windows have at most 1 one: [1,0] [0,0] OK [0,1] [0,0] OK [0,0] [1,0] OK [0,0] [0,1] OK Output: 4 Key Insight: The matrix tiles with sideLength x sideLength patterns. Each position (i%s, j%s) in the template appears a fixed number of times across the matrix. By placing 1s at positions with highest frequency (up to maxOnes per template), we maximize total ones while satisfying the constraint in every sliding window. TutorialsPoint - Maximum Number of Ones | Mathematical Pattern Recognition
Asked in
Google 35 Microsoft 28 Facebook 22 Amazon 18
28.5K Views
Medium Frequency
~45 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen