leetcode801 Minimum Swaps To Make Sequences Increasing (动态规划)
2018-03-19 15:59
876 查看
leetcode801 Minimum Swaps To Make Sequences Increasing (动态规划)
Description
We have two integer sequencesAand
Bof 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,
Aand
Bare 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].
代码
参考leetcode801. Minimum Swaps To Make Sequences Increasing(python)
class Solution: def minSwap(self, A, B): dp = [[len(A),len(A)] for i in range(len(A))] # dp[i][0] 到第i个位置严格递增且不需要交换第i个数 需要交换的次数 # dp[i][1] 到第i个位置严格递增且需要交换第i个数 需要交换的次数 dp[0][0] = 0; dp[0][1] = 1; for i in range(1, len(A)): if A[i] > A[i - 1] and B[i] > B[i - 1]: dp[i][0] = dp[i - 1][0] dp[i][1] = dp[i - 1][1] + 1 if A[i] > B[i - 1] and B[i] > A[i - 1]: dp[i][0] = min(dp[i][0], dp[i - 1][1]) dp[i][1] = min(dp[i][1], dp[i - 1][0] + 1) return min(dp[len(A) - 1][0], dp[len(A) - 1][1])
相关文章推荐
- [LeetCode] Minimum Swaps To Make Sequences Increasing 使得序列递增的最小交换
- 801. Minimum Swaps To Make Sequences Increasing
- 801. Minimum Swaps To Make Sequences Increasing
- 动态规划入门级教学(leetcode)121.Best Time to Buy and Sell Stock
- 【LeetCode】Best Time to Buy and Sell Stock IV 动态规划dp解法(C++)
- Leetcode 462 Minimum Moves to Equal Array Elements II
- leetcode453_Minimum_moves_to_Equal_array
- Leetcode 之 Minimum Moves to Equal Array Elements II
- LeetCode "Minimum Moves to Equal Array Elements"
- [LeetCode 121]Best Time to Buy and Sell Stock(动态规划)
- leetcode 453 Minimum Moves to Equal Array Elements C++
- LeetCode : Minimum Number of Arrows to Burst Balloons
- [leetcode] 452. Minimum Number of Arrows to Burst Balloons
- LeetCode 769. Max Chunks to Make Sorted I题目解析
- leetcode -- 691. Stickers to Spell Word【动态规划 + 位图使用】
- LeetCode Minimum Moves to Equal Array Elements II
- 【LeetCode】Minimum Moves to Equal Array Elements 解题报告
- Minimum number of swaps required to sort an array
- Leetcode(W9):123. Best Time to Buy and Sell Stock III(动态规划)
- [return sum(nums)-min(nums)*len(nums)leetcode453】 Minimum Moves to Equal Array Elements