# Program to find minimum number of operations required to make lists strictly Increasing in python

PythonServer Side ProgrammingProgramming

Suppose we have two list of numbers called A and B, and they are of same length. Now consider we can perform an operation where we can swap numbers A[i] and B[i]. We have to find the number of operations required to make both lists strictly increasing.

So, if the input is like A = [2, 8, 7, 10] B = [2, 4, 9, 10], then the output will be 1, as we can swap 7 in A and 9 in B. Then the lists will be like A = [2, 8, 9, 10] and B = [2, 4, 7, 10] which are both strictly increasing lists.

To solve this, we will follow these steps:

• Define a function dp() . This will take i, prev_swapped
• if size of A is same as i, then
• return 0
• otherwise when i is same as 0, then
• return minimum of dp(i + 1, False) and 1 + dp(i + 1, True)
• otherwise,
• prev_A := A[i - 1]
• prev_B := B[i - 1]
• if prev_swapped is True, then
• swap prev_A and prev_B
• if A[i] <= prev_A or B[i] <= prev_B, then
• return 1 + dp(i + 1, True)
• otherwise,
• ans := dp(i + 1, False)
• if A[i] > prev_B and B[i] > prev_A, then
• ans := minimum of ans, 1 + dp(i + 1, True)
• return ans
• From the main method call the function dp(0, False) and return its value as result

Let us see the following implementation to get better understanding:

## Example Code

Live Demo

class Solution:
def solve(self, A, B):
def dp(i=0, prev_swapped=False):
if len(A) == i:
return 0
elif i == 0:
return min(dp(i + 1), 1 + dp(i + 1, True))
else:
prev_A = A[i - 1]
prev_B = B[i - 1]
if prev_swapped:
prev_A, prev_B = prev_B, prev_A
if A[i] <= prev_A or B[i] <= prev_B:
return 1 + dp(i + 1, True)
else:
ans = dp(i + 1)
if A[i] > prev_B and B[i] > prev_A:
ans = min(ans, 1 + dp(i + 1, True))
return ans

return dp()

ob = Solution()
A = [2, 8, 7, 10]
B = [2, 4, 9, 10]
print(ob.solve(A, B))

## Input

[2, 8, 7, 10], [2, 4, 9, 10]

## Output

1
Published on 25-Nov-2020 12:29:52