# Make Array Strictly Increasing in C++

Suppose we have two arrays arr1 and arr2, these can store integer numbers. We have to find the minimum number of operations needed to make arr1 strictly increasing. Here, we can choose two indices 0 <= i < n and 0 <= j < m and do the assignment arr1[i] = arr2[j] (n and m are the size of arr1 and arr2 respectively)

If we caPending-3nnot make the array arr1 strictly increasing, then return -1.

So, if the input is like arr1 = [1,5,3,7,8], arr2 = [1,3,2,5], then the output will be 1, as we can replace 5 with 2, then the array will be [1,2,3,7,8].

To solve this, we will follow these steps −

• Define a function solve(), this will take an array arr1, an array arr2, i, j, prev, one 2D array dp,

• if i >= size of arr1, then −

• return 1

• j = first element of the subarray of arr2 from arr2[j] and upper

• if dp[i, j] is not equal to -1, then −

• return dp[i, j]

• ret := size of arr2 + 1

• if prev < arr1[i], then −

• ret := minimum of ret and solve(arr1, arr2, i + 1, j, arr1[i], dp)

• if j < size of arr2, then −

• ret := minimum of ret and 1 + solve(arr1, arr2, i + 1, j, arr2[j], dp)

• return dp[i, j] = ret

• From the main method, do the following −

• sort the array arr2

• n := size of arr1

• m := size of arr2

• Define one 2D array dp of size 2005 x 2005 and fill this with -1

• ret := solve(arr1, arr2, 0, 0, -inf, dp)

• return (if ret > size of arr2, then -1, otherwise ret - 1)

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int solve(vector<int>& arr1, vector<int>& arr2, int i, int j, int prev, vector<vector<int> >& dp){
if (i >= arr1.size())
return 1;
j = upper_bound(arr2.begin() + j, arr2.end(), prev) - arr2.begin();
if (dp[i][j] != -1)
return dp[i][j];
int ret = arr2.size() + 1;
if (prev < arr1[i]) {
ret = min(ret, solve(arr1, arr2, i + 1, j, arr1[i], dp));
}
if (j < arr2.size()) {
ret = min(ret, 1 + solve(arr1, arr2, i + 1, j, arr2[j], dp));
}
return dp[i][j] = ret;
}
int makeArrayIncreasing(vector<int>& arr1, vector<int>& arr2){
sort(arr2.begin(), arr2.end());
int n = arr1.size();
int m = arr2.size();
vector<vector<int> > dp(2005, vector<int>(2005, -1));
int ret = solve(arr1, arr2, 0, 0, INT_MIN, dp);
return ret > arr2.size() ? -1 : ret - 1;
}
};
main(){
Solution ob;
vector<int> v = {1,5,3,7,8}, v1 = {1,3,2,5};
cout << (ob.makeArrayIncreasing(v,v1));
}

## Input

{1,5,3,7,8}, {1,3,2,5}

## Output

1