第一行输入两个整数 n 和 m,代表 n*m 的矩阵
接下来输入一个 n*m 的矩阵
输出其中全是 1 的所有矩形区域中,最大的矩形区域里 1 的数量。
1 4 1 1 1 0
3
最大的矩形区域有3个1,所以返回3
N, M= list(map(int,input().split())) histogram = [] for i in range(N): nums = list(map(int,input().split())) histogram.append(nums) #原矩阵 for j in range(M): for i in range(1, N): if histogram[i][j] == 1: histogram[i][j] += histogram[i-1][j] #构造直方图 # 函数: 计算直方图中的最大矩形 def maxRect(nums): stack = [] maxArea = 0 nums.append(0) for i in range(len(nums)): while len(stack)>0 and nums[stack[-1]] > nums[i]: H = nums[stack.pop()] sidx = -1 if len(stack)>0: sidx = stack[-1] area = H * (i-sidx-1) maxArea = max(maxArea, area) stack.append(i) return maxArea maxR = 0 for i in range(N): nums = histogram[i] maxR = max(maxR, maxRect(nums)) #计算每一行 直方图中的最大矩形 print(maxR)