topic
There is a large (m - 1) x (n - 1)
rectangular field whose two opposite corners are (1, 1)
and (m, n)
, and inside the field there are some horizontal and vertical fences, given by the arrays hFences
and , respectively vFences
.
The horizontal fence is the coordinate (hFences[i], 1)
to (hFences[i], n)
, and the vertical fence is the coordinate (1, vFences[i])
to (m, vFences[i])
.
Returns the area of the largest square field that can be formed by removing some ( possibly no ) fences, or returns the area if a square field cannot be formed .-1
Since the answer may be large, return the remainder of the result 109 + 7
pair .
NOTE: The field is surrounded by two horizontal fences (coordinates (1, 1)
to (1, n)
and coordinates (m, 1)
to (m, n)
) and two vertical fences (coordinates (1, 1)
to (m, 1)
and coordinates (1, n)
to (m, n)
). These fences cannot be removed.
Example 1:
Input: m = 4, n = 3, hFences = [2,3], vFences = [2] Output: 4 Explanation: Removing the horizontal fence at 2 and the vertical fence at 2 will result in a square field with area 4 .
Example 2:
Input: m = 6, n = 7, hFences = [2], vFences = [4] Output: -1 Explanation: It can be shown that a square field cannot be formed by removing fences.
hint:
3 <= m, n <= 109
1 <= hFences.length, vFences.length <= 600
1 < hFences[i] < m
1 < vFences[i] < n
hFences
The elements in andvFences
are unique.
Problem: https://leetcode.cn/problems/maximum-squar100169 e-area-by-removing-fences-from-a-field/description/
[TOC]
Ideas
Traverse all the horizontal railings and vertical railings, calculate the difference between the horizontal railings and the difference between the longitudinal railings and store the two sets. The final answer is the square of the intersection of the two sets.
the complexity
time complexity:
O(m^2+n^2)
Space complexity:
O(m+n)
Code
class Solution:
def maximizeSquareArea(self, m: int, n: int, hFences: List[int], vFences: List[int]) -> int:
ans = -1
hFences.append(m)
hFences.insert(0,1)
row = set()
for i in range(len(hFences)):
for j in range(0,i):
row.add(abs( hFences[i] - hFences[j] ))
vFences.append(n)
vFences.insert(0,1)
col = set()
for i in range(len(vFences)):
for j in range(0,i):
col.add(abs(vFences[i] - vFences[j]))
if abs(vFences[i] - vFences[j]) in row :
ans = max(ans,pow(abs(vFences[i] - vFences[j]),2))
for val in row:
if val in col:
ans = max(ans,pow(val,2))
return ans % 1_000_000_007 if