Skip to content

1727. Largest Submatrix With Rearrangements 👍

  • Time: $O(mn\log n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
 public:
  int largestSubmatrix(vector<vector<int>>& matrix) {
    const int n = matrix[0].size();
    int ans = 0;
    vector<int> hist(n);

    for (const vector<int>& row : matrix) {
      // Accumulate the histogram if possible.
      for (int i = 0; i < n; ++i)
        hist[i] = row[i] == 0 ? 0 : hist[i] + 1;

      // Get the sorted histogram.
      vector<int> sortedHist(hist);
      ranges::sort(sortedHist);

      // Greedily calculate the answer.
      for (int i = 0; i < n; ++i)
        ans = max(ans, sortedHist[i] * (n - i));
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int largestSubmatrix(int[][] matrix) {
    final int n = matrix[0].length;
    int ans = 0;
    int[] hist = new int[n];

    for (int[] row : matrix) {
      // Accumulate the histogram if possible.
      for (int i = 0; i < n; ++i)
        hist[i] = row[i] == 0 ? 0 : hist[i] + 1;

      // Get the sorted histogram.
      int[] sortedHist = hist.clone();
      Arrays.sort(sortedHist);

      // Greedily calculate the answer.
      for (int i = 0; i < n; ++i)
        ans = Math.max(ans, sortedHist[i] * (n - i));
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution:
  def largestSubmatrix(self, matrix: list[list[int]]) -> int:
    ans = 0
    hist = [0] * len(matrix[0])

    for row in matrix:
      # Accumulate the histogram if possible.
      for i, num in enumerate(row):
        hist[i] = 0 if num == 0 else hist[i] + 1

      # Get the sorted histogram.
      sortedHist = sorted(hist)

      # Greedily calculate the answer.
      for i, h in enumerate(sortedHist):
        ans = max(ans, h * (len(row) - i))

    return ans