LeetCode 1183. Maximum Number of Ones
原题链接
困难
作者:
JasonSun
,
2020-01-24 07:51:54
,
所有人可见
,
阅读 2945
Algorithm (Greedy)
- We denote the big matrix as $M$, sidelength as $\ell$ We focus on the first square sub-matrix $A$. Note that if we can put $1$ at $A_{ij},$ then by copy and translation of $A$, $M_{a,b}=1$ for all $a\mod\ell=i$ and $b\mod\ell=j$.
- Let $\mathcal{C}(i,j)$ be the set of all possible $M_{a,b}$’s to be assigned $1$ when $A_{ij}$ is $1$. Then the solution is then $$\sum_{k=1}^{\texttt{maxOnes}}\texttt{sortedList}\{|\mathcal{C}(i,j)|\}[k].$$
- This could be solved using a priority queue or a vector. The implementation is standard.
Code
class Solution {
public:
int maximumNumberOfOnes(int width, int height, int sideLength, int maxOnes) {
const auto buildQ = [&](priority_queue<int, std::vector<int>, std::greater<int>> self = {}) {
for (int r = 0; r < sideLength; ++r)
for (int c = 0; c < sideLength; ++c) {
const auto V = (height - 1 - c) / sideLength + 1;
const auto H = (width - 1 - r) / sideLength + 1;
self.emplace(V * H);
if (size(self) > maxOnes)
self.pop();
}
return self;
};
const auto solution = [Q = buildQ()](int acc = 0) mutable {
while (not empty(Q)) {
acc += Q.top();
Q.pop();
}
return acc;
}();
return solution;
}
};