Monday, September 13, 2021

Dynamic Programming - Find Closest Element between 2 arrays - O(n2) time complexity

# Driver Code

A = [6, 1, 12]

B = [1, 0, 8]

C = [0,0,0]

prev = 0

for i in range(0, len(A)):

    prev = 0

    #print("iteration I=", i)

    for j in range (0, len(B)):

        #print("iteration J=", j)

        temp = abs(A[i]-B[j])

        #print("Temp", A[i], B[j], temp, prev)

        if(temp >= 0):

            if(j == 0):

                prev= temp

                C[i] = B[j]

            if(A[i] == B[j]):

                prev = temp

                C[i] = B[j]

                #print("if", temp, prev)

            elif (temp <  prev):

                prev = temp

                C[i]= B[j]

                #print("elif", C[i], prev)

print(C)

Output is: C = [8, 1, 8]