โ† All problems

3195. Find the Minimum Area to Cover All Ones I

MediumOpen on LeetCodeProblem statement

Problem Statement

3195. Find the Minimum Area to Cover All Ones I

Medium


You are given a 2D binary array grid. Find a rectangle with horizontal and vertical sides with the smallest area, such that all the 1's in grid lie inside this rectangle.

Return the minimum possible area of the rectangle.

 

Example 1:

Input: grid = [[0,1,0],[1,0,1]]

Output: 6

Explanation:

The smallest rectangle has a height of 2 and a width of 3, so it has an area of 2 * 3 = 6.

Example 2:

Input: grid = [[1,0],[0,0]]

Output: 1

Explanation:

The smallest rectangle has both height and width 1, so its area is 1 * 1 = 1.

 

Constraints:

Java โ€” simulation

Source file
class Solution {
    public int minimumArea(int[][] grid) {
        int m = grid.length, n = grid[0].length, top = m, btm = -1, lt = n, rt = -1;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    top = Math.min(top, i);
                    btm = Math.max(btm, i);
                    lt = Math.min(lt, j);
                    rt = Math.max(rt, j);
                }
            }
        }
        // System.out.println(top + "\t" + btm + "\t" + lt + "\t" + rt);
        return (btm - top + 1) * (rt - lt + 1);
    }
}