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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code