You are given a 2D array wall
representing a brick wall. Each row in the wall array is an array of positive integers representing the widths of bricks in that row, from left to right. Your goal is to find the minimum number of vertical lines drawn through the entire wall (from top to bottom) that cross the fewest bricks.
For example: If the input is:
[
[1, 2, 2, 1],
[3, 1, 2],
[1, 3, 2],
[2, 4],
[3, 1, 2],
[1, 3, 1, 1]
]
The output should be 2
.
Are the widths of the bricks always positive integers? Yes, the brick widths are always positive integers.
Is the wall always rectangular, height-wise? Yes, each row in the wall may have different numbers of bricks, but the total width of bricks in each row is always the same.
Should we focus on cutting through the least number of bricks or not cutting through any bricks at all if possible? The goal is to minimize the number of bricks cut through.
import java.util.*;
public class BrickWall {
public int leastBricks(List<List<Integer>> wall) {
HashMap<Integer, Integer> edgeCount = new HashMap<>();
int maxEdgeCount = 0;
// Calculate edge positions
for (List<Integer> row : wall) {
int width = 0;
// Exclude the last brick since we should not consider the edge of the wall itself
for (int i = 0; i < row.size() - 1; i++) {
width += row.get(i);
edgeCount.put(width, edgeCount.getOrDefault(width, 0) + 1);
maxEdgeCount = Math.max(maxEdgeCount, edgeCount.get(width));
}
}
return wall.size() - maxEdgeCount;
}
public static void main(String[] args) {
BrickWall solution = new BrickWall();
List<List<Integer>> wall = Arrays.asList(
Arrays.asList(1, 2, 2, 1),
Arrays.asList(3, 1, 2),
Arrays.asList(1, 3, 2),
Arrays.asList(2, 4),
Arrays.asList(3, 1, 2),
Arrays.asList(1, 3, 1, 1)
);
System.out.println(solution.leastBricks(wall)); // Output: 2
}
}
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?