Given two integer arrays arr1
and arr2
, return the minimum number of operations (possibly zero) needed to make arr1
strictly increasing.
In one operation, you can choose two indices 0 <= i < arr1.length
and 0 <= j < arr2.length
and do the assignment arr1[i] = arr2[j]
.
If there is no way to make arr1
strictly increasing, return -1
.
Example 1:
Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4] Output: 1 Explanation: Replace5
with2
, thenarr1 = [1, 2, 3, 6, 7]
.
Example 2:
Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1] Output: 2 Explanation: Replace5
with3
and then replace3
with4
.arr1 = [1, 3, 4, 6, 7]
.
Example 3:
Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]
Output: -1
Explanation: You can't make arr1
strictly increasing.
Constraints:
1 <= arr1.length, arr2.length <= 2000
0 <= arr1[i], arr2[i] <= 10^9
解题思路:
对于arr1的第 i - 1 位,这位可以改,也可以不改。但是都要保证前i- 1位严格递增 ;
设置了一个vector
cnt_max[i]中存的是<修改的次数 , 修改后的最大值> 。
第i位,遍历cnt_max[i - 1]中的每对元素
for(auto ele : cnt_max[i - 1])
{
//不改
if(arr1[i - 1] > ele.second) //可以不改;
//要改
auto it = arr2_num.upper_bound(ele.second) ;
if(it != arr2_num.end())//在arr2_num中可以找到一个比ele.second大的数,可以改
}
如果cnt_max[i].empty(),就直接返回-1 ;
最后返回cnt_max[arr1.size()].begin()->first ;//这个是判断arr1[arr1.size()-1]位改还是不改后的最少修改次数 ;
class Solution {
public:
int makeArrayIncreasing(vector& arr1, vector& arr2)
{
int n1 = arr1.size() ;
vector