Q: You are given an array of n integers. You want to modify the array so that it is increasing, i.e., every element is at least as large as the previous element.
On each move, you may increase the value of any element by one. What is the minimum number of moves required?
Input:
5
3 2 5 1 7
Output: 5
My attempt at the solution:
- input number of elements in list
- input elements of list as string, and convert to a list of integers
- make a function that stores the number of moves as the difference of non-increasing elements. ex: in list [1,2,4,3], 4 is greater than 3, so it is non increasing, so I find the difference between the terms, and add it to the number of moves.
- add the difference to the lesser term (i.e make list [1,2,4,3] into [1,2,4,4])
- call this function whenever i'th term is lesser than (i+1)'th list of list
- Print the total number of moves
My code:
a = input('')
b = list(map(int, a.split(' '))) # split string into a list of numbers
sum1 = 0
def moves(i):
global sum1
for i in range(len(b)-1):
if b[i] < b[i+1]:
sum1 += b[i] - b[i+1]
b[i + 1] += b[i] - b[i+1]
else:
moves(i+1)
print(sum1)
moves(0)
What is wrong in the implementation and how can I correct it?
sum.