class Solution:
def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int:
"""
# time O(N^4) space O(N^2)
step1, cache W,H and create two list for A, B respectively; create a dictionary
step2, loop through whole image, find coordinate where value = 1 in both A, B, and store them into their own list
step3, initialize res, nested for loop through two list storing coordinate tuples, get the difference of x positions and of y positions, store the delta x and delta y into temporary tuple, and save into dictionary as key and cnt # the delta position appeared.
step4, at same time update the max overlap points by comparing current max cnt val based on dictionary with previous max overlap value.
step5, return result after nested loop ends
"""
row = len(A)
col = len(A[0])
a,b = [],[]
d = {}
for i in range(row):
for j in range(col):
if A[i][j] == 1:
a.append((i,j))
if B[i][j] == 1:
b.append((i,j))
res = 0
for tup1 in b:
for tup2 in a:
tup3 = (tup2[0]-tup1[0],tup2[1]-tup1[1])
d[tup3] = d[tup3] + 1 if tup3 in d else 1
res = max(res,d[tup3])
# print(res,d)
return res