Open In App

Minimize swap between same indexed elements to make given Arrays strictly increasing

Last Updated : 20 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays arr1[] and arr2[] of size N each, the task is to find the minimum number of interchange of the same indexed elements required to make both arrays strictly increasing.

Note: Return -1 if it is not possible to make them strictly increasing.

Examples:

Input: arr1 = {1, 3, 5, 4}, arr2 = {1, 2, 3, 7}
Output: 1
Explanation:  
Swap arr1[3] and arr2[3]. 
Then the sequences are:
arr1 = [1, 3, 5, 7] and arr2 = [1, 2, 3, 4] which are both strictly increasing.
Therefore, minimum number of swaps required =1.

Input: arr1 = {0, 3, 5, 8, 9}, nums2 = {2, 1, 4, 6, 9}
Output: 1

 

Approach: The problem can be solved based on the following observation:

For each index there are two choices: either swap the elements or not. If in both cases the prefixes of both arrays are not strictly increasing then it is not possible to perform the task. Otherwise, continue with this approach.

The above observation can be implemented using dynamic programming concept. Create two dp[] arrays where - 

  • The ith index of one will store the minimum steps required to make the prefixes strictly increasing when the current elements are swapped and 
  • The other array will store the minimum steps when the current one is not swapped.

Follow the steps mentioned below to implement the above observation:

  • Consider two arrays swap[] and noswap[] where - 
    • swap[i] stores the minimum steps when arr1[i] & arr2[i] are swapped given the array is sorted from 0 to i-1.
    • noswap[i] st