Program to find minimum operations to make the array increasing using Python
Suppose we have an array nums. In one operation, we can select one element of the array and increase it by 1. For example, if we have [4,5,6], we can select element at index 1 to make the array [4,5,5]. Then we have to find the minimum number of operations required to make nums strictly increasing.
So, if the input is like nums = [8,5,7], then the output will be 7, because we need to increase like [8,6,7],[8,7,7],[8,8,7],[8,9,7],[8,9,8],[8,9,9],[8,9,10].
To solve this, we will follow these steps −
-
count:= 0
-
for i in range 0 to size of nums – 1, do
-
if nums[i+1] −= nums[i], then
-
count := count + nums[i] – nums[i+1] + 1
-
nums[i+1] := nums[i+1] + nums[i] – nums[i+1] + 1
-
-
-
return count
Let us see the following implementation to get better understanding −
Example
Live Demo
def solve(nums): count=0 for i in range(len(nums)-1): if nums[i+1]<=nums[i]: count+=nums[i]-nums[i+1]+1 nums[i+1]+=nums[i]-nums[i+1]+1 return count nums = [8,5,7] print(solve(nums))
Input
[8,5,7]
Output
7
Advertisements
Leave a Reply
You must be logged in to post a comment.