欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LC.801. Minimum Swaps To Make Sequences Increasing

程序员文章站 2022-05-18 10:01:50
...

LC.801. Minimum Swaps To Make Sequences Increasing

class Solution(object):
    def minSwap(self, A, B):
        """
         就是四个对角线元素的之间的关系
         swap[i] 表示在index = i 处发生交换使得两个数列保持递增的总swap次数
         noswap[i] 表示在index = i 处不发生交换使得两个数列保持递增的总swap次数
         注意初始值,并且每次swap后次数都要+1
        """
        swap = [float("inf")] * len(A)
        no_swap = [float("inf")] * len(A)
        for i in range(len(A)):
            if i == 0:
                swap[0], no_swap[0] = 1,0
            else:
                if A[i] > A[i-1] and B[i] > B[i-1]:
                    no_swap[i] = min(no_swap[i], no_swap[i-1])
                    swap[i] = min(swap[i], swap[i-1]+1)
                if A[i] > B[i-1] and B[i] > A[i-1]:
                    no_swap[i] = min(no_swap[i], swap[i-1])
                    swap[i] = min(swap[i], no_swap[i-1]+1)
        return min(swap[-1], no_swap[-1])