Skip to content

Instantly share code, notes, and snippets.

@droneru
Created January 20, 2019 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save droneru/46408d8168955844ec02fdb621d9b9b9 to your computer and use it in GitHub Desktop.
Save droneru/46408d8168955844ec02fdb621d9b9b9 to your computer and use it in GitHub Desktop.
Максимальная площадь прямоугольника в квадратной матрице за O(N^3)
package ru.drone.ya;
public class MaxRectangleN3 {
/**
* Максимальная площадь прямоугольника в квадратной матрице
*/
public long getMaxRectangleSquare(int[][] m) {
int[] cursor = new int[m.length];
long max = 0;
for (int row = 0; row < m.length; row++) {
for (int i = 0; i < cursor.length; i++)
cursor[i] = m[row][i] == 0 ? 0 : cursor[i] + 1;
max = Long.max(max, getMaxRectangleSquare(cursor));
}
return max;
}
/** a - строка с высотами*/
private long getMaxRectangleSquare(int[] a) {
long maxSq = a[0];
for (int left = 0; left < a.length; left++) {
long minH = a[left];//минимальная высота на отрезке от left до right
for (int right = left; right < a.length; right++) {
minH = Long.min(minH, a[right]);
maxSq = Long.max(maxSq, minH * (1 + right - left));
}
}
return maxSq;
}
public static void main(String[] args) {
int[][] m = new int[][]{
{1, 1, 1, 1, 1},
{1, 1, 1, 1, 1},
{1, 1, 1, 1, 1},
{1, 1, 1, 1, 1},
{1, 1, 1, 1, 1}
};
System.out.println("TEST 1 expected: 25, actual: " + new MaxRectangleN3().getMaxRectangleSquare(m));
m = new int[][]{
{0, 0, 1, 1, 1},
{0, 0, 1, 0, 1},
{1, 1, 1, 1, 0},
{1, 0, 1, 1, 1},
{1, 1, 1, 1, 0}
};
System.out.println("TEST 2 expected: 6, actual: " + new MaxRectangleN3().getMaxRectangleSquare(m));
m = new int[][]{
{0, 1, 1, 1, 1},
{1, 1, 1, 1, 1},
{1, 1, 1, 1, 1},
{1, 1, 1, 1, 1},
{1, 1, 1, 0, 1}
};
System.out.println("TEST 3 expected: 16, actual: " + new MaxRectangleN3().getMaxRectangleSquare(m));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment