|
| 1 | +/* |
| 2 | +Make Array Strictly Increasing |
| 3 | +Link: https://leetcode.com/problems/make-array-strictly-increasing/ |
| 4 | +
|
| 5 | +Given two integer arrays arr1 and arr2, return the minimum number of operations (possibly zero) needed to make arr1 strictly increasing. |
| 6 | +
|
| 7 | +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]. |
| 8 | +
|
| 9 | +If there is no way to make arr1 strictly increasing, return -1. |
| 10 | +
|
| 11 | +Example 1: |
| 12 | +Input: arr1 = [1,5,3,6,7], arr2 = [1,3,2,4] |
| 13 | +Output: 1 |
| 14 | +Explanation: Replace 5 with 2, then arr1 = [1, 2, 3, 6, 7]. |
| 15 | +
|
| 16 | +Example 2: |
| 17 | +Input: arr1 = [1,5,3,6,7], arr2 = [4,3,1] |
| 18 | +Output: 2 |
| 19 | +Explanation: Replace 5 with 3 and then replace 3 with 4. arr1 = [1, 3, 4, 6, 7]. |
| 20 | +
|
| 21 | +Example 3: |
| 22 | +Input: arr1 = [1,5,3,6,7], arr2 = [1,6,3,3] |
| 23 | +Output: -1 |
| 24 | +Explanation: You can't make arr1 strictly increasing. |
| 25 | +
|
| 26 | +Constraints: |
| 27 | +1 <= arr1.length, arr2.length <= 2000 |
| 28 | +0 <= arr1[i], arr2[i] <= 10^9 |
| 29 | + */ |
| 30 | +package com.raj; |
| 31 | + |
| 32 | +public class MakeArrayStrictlyIncreasing { |
| 33 | + public static void main(String[] args) { |
| 34 | + // Initialization. |
| 35 | + int[] arr1 = {1, 5, 3, 6, 7}; |
| 36 | + int[] arr2 = {1, 3, 2, 4}; |
| 37 | + int ans = 1; |
| 38 | + |
| 39 | + // Logic. |
| 40 | + for (int i = 0; i < arr1.length - 1; i++) { |
| 41 | + if (arr1[i] >= arr1[i + 1]) { |
| 42 | + boolean valueFound = false; |
| 43 | + if (i == 0) { |
| 44 | + for (int j : arr2) { |
| 45 | + if (arr1[i + 1] > j) { |
| 46 | + valueFound = true; |
| 47 | + break; |
| 48 | + } |
| 49 | + } |
| 50 | + } else { |
| 51 | + for (int j : arr2) { |
| 52 | + if (arr1[i - 1] < j && arr1[i + 1] > j) { |
| 53 | + valueFound = true; |
| 54 | + break; |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + if (!valueFound) { |
| 60 | + ans = -1; |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + if (ans == 1 && arr1[arr1.length - 2] >= arr1[arr1.length - 1]) { |
| 66 | + boolean valueFound = false; |
| 67 | + for (int j : arr2) { |
| 68 | + if (arr1[arr1.length - 2] < j) { |
| 69 | + valueFound = true; |
| 70 | + break; |
| 71 | + } |
| 72 | + } |
| 73 | + if (!valueFound) { |
| 74 | + ans = -1; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + // Display the result. |
| 79 | + if (ans == 1) { |
| 80 | + System.out.println("Yes, array can be made strictly increasing using the values from another array."); |
| 81 | + } else { |
| 82 | + System.out.println("No, array can not be made strictly increasing using the values from another array."); |
| 83 | + } |
| 84 | + } |
| 85 | +} |
0 commit comments