Sponsored
Sponsored
This solution involves shifting one image over another in all possible positions and counting how many ones overlap. By varying the horizontal and vertical shifts, and calculating overlaps with respect to the position of img2
, the solution finds the maximum overlap. This approach iterates over all possible translations, moving img1
relative to img2
and keeping track of the maximum overlap seen.
Time Complexity: O(n^4), where n is the size of the matrix, due to the two nested loops and a cross-sectional overlap check for each.
Space Complexity: O(1), since the solution uses constant space apart from input storage.
1def largestOverlap(img1, img2):
2 def overlap_count(xShift, yShift):
3 n = len(img1)
4 count = 0
5 for r in range(n):
6 for c in range(n):
7 if 0 <= r + xShift < n and 0 <= c + yShift < n:
8 count += img1[r][c] & img2[r + xShift][c + yShift]
9 return count
10
11 n = len(img1)
12 max_overlap = 0
13 for xShift in range(-n + 1, n):
14 for yShift in range(-n + 1, n):
15 max_overlap = max(max_overlap, overlap_count(xShift, yShift))
16 return max_overlap
17
18img1 = [[1,1,0],[0,1,0],[0,1,0]]
19img2 = [[0,0,0],[0,1,1],[0,0,1]]
20print("Max Overlap:", largestOverlap(img1, img2))
In the Python implementation, we define an inner function overlap_count
that calculates overlapping 1s for shifts. The main logic consists of nested loops attempting all possible shifts and updating the maximum overlap counter. The result outputs through a print statement call.
This solution uses the concept of convolution by considering the images as arrays of points. We tallied the number of overlapping 1s for each relative translation using convolution properties without directly shifting arrays and used efficient matrix operations to compute overlaps.
Time Complexity: O(n^4), as it traverses through each overlap position and checks all cells.
Space Complexity: O(n), due to the allocation of cumulative arrays.
1
For Java, arrays of coordinates store 1s efficiently. By translating shifts as strings for keys, a hashmap tracks overlaps, utilizing precise 1-position counting rather than relying on whole-matrix shifts.