Maximum Number of Ones - Problem
Maximum Number of Ones is a fascinating optimization problem that challenges you to think about overlapping constraints.
You need to construct a binary matrix (containing only 0s and 1s) with dimensions
Your goal is to determine the maximum possible number of ones that can be placed in the entire matrix while respecting this constraint.
π― Key Insight: This isn't just about placing ones randomly - you need to understand how different positions in the matrix contribute to multiple overlapping sub-matrices, and optimize accordingly!
You need to construct a binary matrix (containing only 0s and 1s) with dimensions
width Γ height. However, there's a crucial constraint: every square sub-matrix of size sideLength Γ sideLength can contain at most maxOnes ones.Your goal is to determine the maximum possible number of ones that can be placed in the entire matrix while respecting this constraint.
π― Key Insight: This isn't just about placing ones randomly - you need to understand how different positions in the matrix contribute to multiple overlapping sub-matrices, and optimize accordingly!
Input & Output
example_1.py β Basic Case
$
Input:
width = 3, height = 3, sideLength = 2, maxOnes = 1
βΊ
Output:
4
π‘ Note:
We can place ones at positions forming a checkerboard pattern within the constraints. Each 2Γ2 sub-matrix contains exactly 1 one, and we maximize the total count.
example_2.py β Larger Matrix
$
Input:
width = 2, height = 2, sideLength = 2, maxOnes = 2
βΊ
Output:
2
π‘ Note:
The entire matrix is one 2Γ2 sub-matrix, so we can place at most 2 ones anywhere in the matrix.
example_3.py β Edge Case
$
Input:
width = 1, height = 1, sideLength = 1, maxOnes = 1
βΊ
Output:
1
π‘ Note:
Single cell matrix with single cell sub-matrices. We can place 1 one in the single available position.
Constraints
- 1 β€ width β€ 103
- 1 β€ height β€ 103
- 1 β€ sideLength β€ min(width, height)
- 1 β€ maxOnes β€ sideLength2
Visualization
Tap to expand
Understanding the Visualization
1
Identify Patterns
Every position (i,j) belongs to equivalence class (i%sideLength, j%sideLength)
2
Count Frequencies
Count how many matrix positions belong to each equivalence class
3
Greedy Selection
Sort classes by frequency and select the top maxOnes classes
4
Calculate Result
Sum the frequencies of selected classes
Key Takeaway
π― Key Insight: By recognizing that positions with the same modular coordinates (i%sideLength, j%sideLength) participate in constraints identically, we can group them into equivalence classes and apply a greedy strategy to maximize the total number of ones.
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code