[LeetCode] Maximum Number of Ones

1183. Maximum Number of Ones

Consider a matrix M with dimensions width height, such that every cell has value 0 or 1, and any square sub-matrix of M of size sideLength sideLength has at most maxOnes ones.

Return the maximum possible number of ones that the matrix M can have.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
int maximumNumberOfOnes(int width, int height, int sideLength, int maxOnes) {
unordered_map<int, int> freq;
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
freq[((i % sideLength) * sideLength + (j % sideLength))]++;
}
}
priority_queue<int> pq;
for(auto& [_, c] : freq)
pq.push(c);
int res = 0;
while(!pq.empty() and maxOnes) {
res += pq.top(); pq.pop();
maxOnes--;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/25/PS/LeetCode/maximum-number-of-ones/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.