LeetCode 1187: Make Array Strictly Increasing Solution
Master LeetCode problem 1187 (Make Array Strictly Increasing), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1187. Make Array Strictly Increasing
Problem Explanation
Explanation:
To solve this problem, we can use dynamic programming. We will create a 2D dp array to keep track of the minimum number of operations needed to make a subarray of arr1 strictly increasing up to index i. We will iterate through both arr1 and arr2 and update our dp array accordingly.
At each index i of arr1, we have two choices:
- If
arr1[i] > arr1[i-1], we can keeparr1[i]as is without any operations. - If
arr1[i] <= arr1[i-1], we need to find a suitable value fromarr2to replacearr1[i]to make it strictly increasing. We check all possible values inarr2and choose the one that minimizes the number of operations.
After filling the dp array, we will find the minimum operations needed to make the entire arr1 strictly increasing by considering the last index of the dp array.
Time Complexity:
The time complexity of this approach is O(n^2), where n is the length of arr1.
Space Complexity:
The space complexity is O(n), where n is the length of arr1.
:
Solution Code
class Solution {
public int makeArrayIncreasing(int[] arr1, int[] arr2) {
Arrays.sort(arr2);
int n = arr1.length;
int[][] dp = new int[n + 1][n + 1];
for (int i = 0; i <= n; i++) {
Arrays.fill(dp[i], Integer.MAX_VALUE);
}
dp[0][0] = -1;
for (int i = 1; i <= n; i++) {
int prevVal = dp[i - 1][0];
for (int j = 0; j <= n; j++) {
if (arr1[i - 1] > prevVal) {
dp[i][j] = Math.min(dp[i][j], dp[i - 1][j]);
}
if (j > 0) {
int replaceIdx = Arrays.binarySearch(arr2, prevVal + 1);
if (replaceIdx < 0) {
replaceIdx = -(replaceIdx + 1);
}
if (replaceIdx < arr2.length) {
dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + 1);
}
}
if (j < n) {
prevVal = arr1[i - 1];
}
}
}
int res = Integer.MAX_VALUE;
for (int j = 0; j <= n; j++) {
if (dp[n][j] != Integer.MAX_VALUE) {
res = Math.min(res, dp[n][j]);
}
}
return res == Integer.MAX_VALUE ? -1 : res;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1187 (Make Array Strictly Increasing)?
This page provides optimized solutions for LeetCode problem 1187 (Make Array Strictly Increasing) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1187 (Make Array Strictly Increasing)?
The time complexity for LeetCode 1187 (Make Array Strictly Increasing) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1187 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1187 in Java, C++, or Python.