We have two integer sequences A and B of the same non-zero length.
We are allowed to swap elements A[i] and B[i]. Note that both elements are in the same index position in their respective sequences.
At the end of some number of swaps, A and B are both strictly increasing. (A sequence is strictly increasing if and only if A[0] < A[1] < A[2] < … < A[A.length - 1].)
Given A and B, return the minimum number of swaps to make both sequences strictly increasing. It is guaranteed that the given input always makes it possible.
Example:
Input: A = [1,3,5,4], B = [1,2,3,7]
Output: 1
Explanation:
Swap A[3] and B[3]. Then the sequences are:
A = [1, 3, 5, 7] and B = [1, 2, 3, 4]
which are both strictly increasing.
Note:
A, B are arrays with the same length, and that length will be in the range [1, 1000].
A[i], B[i] are integer values in the range [0, 2000].
给出A,B两个数组,可以交换相同的i 位数字,使得A和B都变成单调升序列。
思路:
和714.买卖股票收手续费的DP有点像,也是准备两个DP数组。一个是交换的情况,一个是keep的情况。
因为一个序列的一段,比如A=[3,5] 和B=[2, 3],可以选择保持不动,就这样A,B都是升序的,也可以交换,但是交换了第一位就要交换第二位。
这时有两个DP数组,keep和swap,keep[i] 和 swap[i]都保存交换的次数。
keep[0]不交换, 所以keep[0] = 0, swap[0]表示交换第0位,swap[0]=1
然后看i = 1,因为A[1] > A[0] 且 B[1] > B[0],就表示A和B已经都是升序的,那么不交换也可以,keep[i] = keep[i-1],表示i-1, i都不交换
swap[1]表示要交换A[1], B[1],那么就必须同时交换A[0]和B[0],所以swap[i] = swap[i-1]+1, 表示i-1, i都交换
如果出现A = [5,4], B = [3,7](example中最后一段),那上面的已经是升序的条件就不满足,如果想让交换一位后满足升序的条件,就必须满足A[i] > B[i-1] && B[i] > A[i-1],那么无论是交换A[i], B[i],还是交换A[i-1], B[i-1],交换后A和B都会是升序的。
这种情况下两种情况,1.交换A[i], B[i],那么就是i-1步不变,因此swap[i] = min(swap[i], keep[i-1] + 1)
2.交换A[i-1], B[i-1], 那么第i步不变,keep[i] = min(keep[i], swap[i-1])
keep[i]简言之就是想要保持第 i 位不变,同时满足A,B都是升序。要么A,B已经是升序,即保持keep[i];要么前面i-1位已经做了变换,使A,B变成升序,即swap[i-1],这两者取较小。
同理swap[i]就是第 i 位要交换,可以第i-1位不交换,只交换第i位,即keep[i-1] + 1;也可以i-1位也换,i位也换,即swap[i-1]+1(这一步是已经满足升序条件时就算出的)。两者取较小。
public int minSwap(int[] A, int[] B) {
if(A == null || B == null || A.length <= 1) {
return 0;
}
int n = A.length;
int[] keep = new int[n];
int[] swap = new int[n];
Arrays.fill(keep, Integer.MAX_VALUE);
Arrays.fill(swap, Integer.MAX_VALUE);
keep[0] = 0;
swap[0] = 1;
for(int i = 1; i < n; i++) {
//不需要交换的情况
if(A[i] > A[i-1] && B[i] > B[i-1]) {
keep[i] = keep[i-1]; //不交换的情况
swap[i] = swap[i-1] + 1; //i-1交换的话,i也要交换
}
//要交换且交换后是升序的情况
if(B[i] > A[i-1] && A[i] > B[i-1]) {
keep[i] = Math.min(keep[i], swap[i-1]);
swap[i] = Math.min(swap[i], keep[i-1] + 1);
}
}
return Math.min(keep[n-1], swap[n-1]);
}