some interesting problem

2 min read

Image Overlap

Two images A and B are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.) We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation is the number of positions that have a 1 in both images. (Note also that a translation does not include any kind of rotation.) What is the largest possible overlap?

Example

Example 1: Input: A = [[1,1,0],[0,1,0],[0,1,0]],B = [[0,0,0],[0,1,1],[0,0,1]] Output: 3 Explanation: We slide A to right by 1 unit and down by 1 unit.

Example 2: [[1]] [[0]] Input: A = [[1]],B = [[0]] Output: 0 Explanation: There is no overlap between the two matrices no matter how they are converted.

Notice

  1. 1 <= A.length = A[0].length = B.length = B[0].length <= 30
  2. 0 <= A[i][j], B[i][j] <= 1

    class Solution:
    """
    @param A: the matrix A
    @param B: the matrix B
    @return: maximum possible overlap
    """
    def largestOverlap(self, A, B):
        # Write your code here.
        A = [(i, j) for i, row in enumerate(A) for j, item in enumerate(row) if item]
        B = [(i, j) for i, row in enumerate(B) for j, item in enumerate(row) if item]
        count = collections.Counter((ax-bx, ay-by) for ax, ay in A for bx, by in B)
        #print(count)
        return max(count.values() or [0])

get k-num-subarray of max number preserving the relative order of the digits

def get_max_number(nums, k):
    """
    :type nums: List[int]
    :type k: int
    :rtype: List[int]
    """
    drop = len(nums) - k
    out = []
    for num in nums:
        while drop and out and out[-1] < num:
            out.pop()
            drop -= 1
        out.append(num)
    return out[:k]

longest increasing subsequence (LIS) algorithm

class Solution:
    """
    @param nums: An integer array
    @return: The length of LIS (longest increasing subsequence)
    """
    def longestIncreasingSubsequence(self, nums):
        # write your code here
        lis=[]
        import bisect
        for n in nums:
            pos=bisect.bisect_left(lis, n)
            if pos==len(lis):
                lis.append(n)
            else:
                lis[pos]=n
            print lis
        return len(lis)