Program to find minimum numbers of function calls to make target array using Python

PythonServer Side ProgrammingProgramming

Suppose we have following function definition:

def modify(arr, op, index):
   if op == 0:
      arr[index] += 1
   if op == 1:
      for i in range(len(arr)):
         arr[i] *=2

We have to find minimum number of function calls required to make a given array nums from one zero array of same size?

So, if the input is like nums = [1,5,3], then the output will be 7 because, initially all elements are 0, [0,0,0]

  • At first step increase second element by 1, so array is [0,1,0]

  • Double second element to make it [0,2,0]

  • Increase third element by 1, so array is [0,2,1]

  • Double elements from index 1 to 2, so array is [0,4,2]

  • Increase all elements by 1 [three operations in total here]

so total 3+4 = 7 operations required.

To solve this, we will follow these steps −

  • ans := an array with two elements all are 0

  • for each n in nums, do

    • double := 0

    • while n is non-zero, do

      • if n is odd, then

        • n := quotient of n/2

        • double := double + 1

      • otherwise,

        • n := n - 1

        • ans[0] := ans[0] + 1

    • ans[1] := maximum of ans[1] and double

  • return sum of all elements of ans

Let us see the following implementation to get better understanding −

Example

 Live Demo

def solve(nums):
   ans = [0, 0]
   for n in nums:
      double = 0
      while(n):
         if not n%2:
            n = n//2
            double+=1
         else:
            n-=1
            ans[0]+=1
            ans[1] = max(ans[1], double)
   return sum(ans)
nums = [1,5,3]
print(solve(nums))

Input

[1,5,3]

Output

7
raja
Published on 28-May-2021 13:06:40
Advertisements