1714. Longest Fence of Ones

Hard7.5 points estimatedMonotonic StackMatrixStack

A farmer keeps a rectangular field divided into square plots: grid[i][j] = 1 means the plot is planted and 0 means it is bare. She wants to fence a block of plots that is completely planted, and fencing costs by perimeter. Return the largest perimeter 2 * (height + width) of an axis-aligned rectangle of plots that contains only 1 values, measured in plot sides, or 0 if the field has no planted plot. With m rows and n columns, m * n <= 2 * 10^5. A perimeter-maximal rectangle can always be widened until it is blocked, so you only need to examine each bar of each row's column-height histogram across its full span; aim for O(m * n) time and O(n) extra space using a monotonic stack.

Example 1

Input:
grid = [[1,0],[1,1]]
Output:
6
Explanation:

The bottom row is a 1 by 2 block and the left column a 2 by 1 block; both have perimeter 6.

Example 2

Input:
grid = [[0,0],[0,0]]
Output:
0
Explanation:

No plot is planted, so no fence can be built.

Example 3

Input:
grid = [[1,1,1],[1,1,1]]
Output:
10
Explanation:

The whole 2 by 3 field is planted, giving perimeter 2 * (2 + 3) = 10.

Constraints

1 ≤ m, n

m * n ≤ 2 * 105

grid[i][j] is 0 or 1

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,000 msC++ 250 msJava 500 msJavaScript 500 msTypeScript 500 ms

Expected complexity

Time
O(m * n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…