给你两个整数数组 arr1 和 arr2,返回使 arr1 严格递增所需要的最小「操作」数(可能为 0)。
每一步「操作」中,你可以分别从 arr1 和 arr2 中各选出一个索引,分别为 i 和 j,0 <= i < arr1.length 和 0 <= j < arr2.length,然后进行赋值运算 arr1[i] = arr2[j]。
如果无法让 arr1 严格递增,请返回 -1。
示例 1:
输入:arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]
输出:1
解释:用 2 来替换 5,之后 arr1 = [1, 2, 3, 6, 7]。
示例 2:
输入:arr1 = [1,5,3,6,7], arr2 = [4,3,1]
输出:2
解释:用 3 来替换 5,然后用 4 来替换 3,得到 arr1 = [1, 3, 4, 6, 7]。
示例 3:
输入:arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]
输出:-1
解释:无法使 arr1 严格递增。
提示:
1 <= arr1.length, arr2.length <= 2000
0 <= arr1[i], arr2[i] <= 10^9
Intuition
For any operation, we need to pick the smallest possible element from the second array. So, we can start by sorting the second array.
Solution
Run the search with two branches:
- Keep the current element (if increasing),
- add an operation.
Return the minimum of these branches. For memoisation, use indexes of the first and second arrays.
基于上述思路,状态应表示为[i1, i2, prev],但是由于i2与prev有直接关系,因此状态可以简化为[i1, i2],关于这点,题解作者是这样解释的: i2
is in the direct correlation with prev
. We could also memoise on [i1][prev] but prev
can be quite large (so we would use a hash map).
class Solution { public: int makeArrayIncreasing(vector<int>& arr1, vector<int>& arr2) { int len1 = arr1.size(), len2 = arr2.size(); sort(arr2.begin(), arr2.end()); vector<vector<int>> dp(len1+1, vector<int>(len2+1, -1)); int result = dfs(0, 0, INT_MIN, arr1, arr2, dp); return result < 2001 ? result : -1; } int dfs(int idx1, int idx2, int prev, vector<int> &arr1, vector<int> &arr2, vector<vector<int>> &dp){ if(idx1 >= arr1.size()) return 0; if(dp[idx1][idx2] >= 0) return dp[idx1][idx2]; int result = 2001; if(arr1[idx1] > prev) result = min(result, dfs(idx1+1, idx2, arr1[idx1], arr1, arr2, dp)); idx2 = upper_bound(arr2.begin()+idx2, arr2.end(), prev) - arr2.begin(); if(idx2 < arr2.size()) result = min(result, dfs(idx1+1, idx2+1, arr2[idx2], arr1, arr2, dp)+1); return dp[idx1][idx2] = result; } };