Program to find minimum number of increments on subarrays to form a target array in Python

PythonServer Side ProgrammingProgramming

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]




Published on 06-Oct-2021 08:54:33