1727. Largest Submatrix With Rearrangements
not modify inputT: O(m*(n+nlogn+n)
S: O(n + n)```java
class Solution {
public int largestSubmatrix(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int result = 0;
int[] maxHeight = new int[n]; // for each col, max height can be.. ? (from height to x, all 1 is the max height)
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[i][j] == 0) {
maxHeight[j] = 0; // once there is a 0 in this row's any col, reset height to 0
} else {
maxHeight[j] += 1;
}
}
// for each row, we all need to cal max area, because sometimes ans is in part area
int[] newHeight = Arrays.copyOf(maxHeight, maxHeight.length);
Arrays.sort(newHeight);
// sort it! like rearrage, so height is ascending, for calculating max area, 小的高會限制大的, 所以小的高排前面
for (int j = 0; j < n; j++) {
result = Math.max(result, newHeight[j]*(n-j)); // cal max area: heigh*width
}
}
return result;
}
}
/***
not modify input
refer to
https://leetcode.com/problems/largest-submatrix-with-rearrangements/solutions/1020710/c-clean-and-clear-with-intuitive-pictures-o-m-n-logn/?envType=daily-question&envId=2023-11-26
T: O(m*(n+nlogn+n)
S: O(n + n)
*/
```modify input
Last updated
Was this helpful?