Skip to content

1183. Maximum Number of Ones 👍

  • Time: $O(\texttt{width} \cdot \texttt{height} + \texttt{sideLength} \log \texttt{sideLength})$
  • Space: $O(\texttt{sideLength}^2)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
 public:
  int maximumNumberOfOnes(int width, int height, int sideLength, int maxOnes) {
    int ans = 0;
    vector<vector<int>> submatrix(sideLength, vector<int>(sideLength));
    priority_queue<int> maxHeap;

    for (int i = 0; i < width; ++i)
      for (int j = 0; j < height; ++j)
        ++submatrix[i % sideLength][j % sideLength];

    for (const auto& row : submatrix)
      for (const int a : row)
        maxHeap.push(a);

    for (int i = 0; i < maxOnes; ++i)
      ans += maxHeap.top(), maxHeap.pop();

    return ans;
  }
};
 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) {
    int ans = 0;
    int[][] submatrix = new int[sideLength][sideLength];
    Queue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder());

    for (int i = 0; i < width; ++i)
      for (int j = 0; j < height; ++j)
        ++submatrix[i % sideLength][j % sideLength];

    for (int[] row : submatrix)
      for (final int a : row)
        maxHeap.offer(a);

    for (int i = 0; i < maxOnes; ++i)
      ans += maxHeap.poll();

    return ans;
  }
}
1
2
3
4
5
6
7
8
9
class Solution:
  def maximumNumberOfOnes(self, width: int, height: int, sideLength: int, maxOnes: int) -> int:
    submatrix = [[0] * sideLength for _ in range(sideLength)]

    for i in range(width):
      for j in range(height):
        submatrix[i % sideLength][j % sideLength] += 1

    return sum(heapq.nlargest(maxOnes, [a for row in submatrix for a in row]))