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: 3×3 Matrix, 2×2 Constraint ≤1101000101Optimal Configuration2×2 sub-matriceseach ≤ 1 oneConstraint Check:Top-left 2×2: 1+0+0+0 = 1 ✓Top-right 2×2: 0+1+0+0 = 1 ✓Bottom-left 2×2: 0+0+1+0 = 1 ✓Bottom-right 2×2: 0+0+0+1 = 1 ✓Total Ones: 4 (Maximum Possible)Key Insight: Place ones in cornersEach corner appears in fewest sub-matrices
Understanding the Visualization
1
Input Matrix
3×3 matrix with 2×2 sub-matrix constraint ≤1 one
2
Constraint Analysis
Identify overlapping sub-matrices and their limits
3
Optimal Placement
Place ones to maximize count while satisfying constraints
Key Takeaway
🎯 Key Insight: Optimal placement requires mathematical analysis of overlapping constraints, not brute force enumeration
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