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

PythonServer Side ProgrammingProgramming

#### Beyond Basic Programming - Intermediate Python

Most Popular

36 Lectures 3 hours

#### Practical Machine Learning using Python

Best Seller

91 Lectures 23.5 hours

#### Practical Data Science using Python

22 Lectures 6 hours

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 := ans + 1

• ans := maximum of ans 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+=1
ans = max(ans, double)
return sum(ans)
nums = [1,5,3]
print(solve(nums))

## Input

[1,5,3]

## Output

7