
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Minimum Operations to Make 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
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