设置两个DP数字,keep和swap, keep 表示,当前位置不交换,总共最少的操作次数,swap表示,当前位置交换,则总共最少的操作次数。
class Solution:
def minSwap(self, A: List[int], B: List[int]) -> int:
N = len(A)
keep = [float('inf') for _ in range(N)] #if the we keep the element at position i for both A and B, the minimum operation we have done so far
swap = [float('inf') for _ in range(N)] #if the we swap the element at position i for both A and B, the minimum operation we have done so far
keep[0] = 0
swap[0] = 1
for i in range(1, N):
if A[i] > A[i-1] and B[i] > B[i-1]:
keep[i] = keep[i-1]
swap[i] = swap[i-1] + 1
if A[i] > B[i-1] and B[i] > A[i-1]:
keep[i] = min(keep[i], swap[i-1])
swap[i] = min(swap[i], keep[i-1] + 1)
return min(keep[N-1], swap[N-1])
当A[i] > A[i-1] and B[i] > B[i-1]时,当前位置保持不变,则其可以等于前一个位置不交换所积累的操作数,当前位置交换,则等于前一个位置也做交换所积累的操作次数再加1(本次交换)。当A[i] > B[i-1] and B[i] > A[i-1],当前位置可以交换,则,如果保留当前位置数字,前一个位置的一对数字可以做交换,所以选择二者最小的操作次数。做交换,则前一对数字可以做保留,同样选择二者最小的操作次数。