- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- 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

Suppose we have an array called target with positive values. Now consider an array initial of same size with all zeros. We have to find the minimum number of operations required to generate a target array from the initial if we do this operation: (Select any subarray from initial and increment each value by one.)

So, if the input is like target = [2,3,4,3,2], then the output will be 4 because initially array was [0,0,0,0,0] first pass select subarray from index 0 to 4 and increase it by 1, so array will be [1,1,1,1,1], then again select from index 0 to 4 to make it [2,2,2,2,2], then select elements from index 1 to 3 and increase, so array will be [2,3,3,3,2], and finally select index 2 and make the array [2,3,4,3,2] which is same as target.

To solve this, we will follow these steps −

prev_num := 0

steps := 0

for each val in target, do

steps := steps + val - prev_num if val > prev_num otherwise 0

prev_num := val

return steps

Let us see the following implementation to get better understanding

def solve(target): prev_num = 0 steps = 0 for val in target: steps += val-prev_num if val > prev_num else 0 prev_num = val return steps target = [2,3,4,3,2] print(solve(target))

[2,3,4,3,2]

4

- Related Questions & Answers
- Program to find number of ways to form a target string given a dictionary in Python
- Program to find minimum number of buses required to reach final target in python
- Program to find maximum number of non-overlapping subarrays with sum equals target using Python
- Program to find minimum numbers of function calls to make target array using Python
- Program to find number of ways to split array into three subarrays in Python
- Program to find minimum number of subsequence whose concatenation is same as target in python
- Program to find most occurring number after k increments in python
- Program to find minimum distance to the target element using Python
- Program to count minimum number of operations to flip columns to make target in Python
- Program to find number of combinations of coins to reach target in Python
- Program to find minimum element addition needed to get target sum in Python
- Program to find number of given operations required to reach Target in Python
- Program to count number of nice subarrays in Python
- Program to find minimum elements to add to form a given sum in Python
- Program to find minimum steps to reach target position by a chess knight in Python

Advertisements