Jack and Jill were going through a jungle to city. They encountered a monster who
told they will only be allowed to escape when they solve a puzzle for him. They
didn't have a choice so they agreed.
He states problem like : I have n buckets having 0 fruits in each bucket initially. I will
give you n numbers denoting fruits required at nth position. But you need to keep 2
simple rules:
1) Either you can increment fruit count by 1 in each bucket i.e. Incremental Operation
2) Or you can double the fruits in each bucket i.e. Doubling operation.
Function Description:
Provide implementation for method play_the_game(target).
play_the_game has the following parameter(s):
target: an integer list denoting numbers of fruits required at nth position.
Example:
Input: 23
Output: 4
Explanation:
To get the target bucket from (0, 0), we
first increment both elements by 1 (2
operations), then double the array (1
operation). Finally increment second
element (1 more operation)
Input: 16 16 16
Output: 7
Explanation:
Answers
Answer: #this is only function you have to use
class Solution:
def countMinOperations(self, arr, n):
arr.sort()
count=0
while(arr.count(0)!=n):
for i in range(n):
if(arr[i]%2==1):
arr[i]=arr[i]-1 #first make all terms even
count=count+1
for i in range(n):
arr[i]=arr[i]//2 #then take half
count=count+1
return count-1
Explanation:
What we have to do here is reduce the no. fruits in all baskets to zero. So first we would identify the baskets with odd fruits and reduce them by one and increment the count for each reduction operation
Then we will take half of all these basket fruits in one operation. We will keep doing this until all baskets have zero fruits.
In the end I returned count-1 as at the last step even when all baskets have zero fruits, count is incremented by one.
Hope this helps you!!
#this is only function you have to use
class Solution:
def countMinOperations(self, arr, n):
arr.sort()
count=0
while(arr.count(0)!=n):
for i in range(n):
if(arr[i]%2==1):
arr[i]=arr[i]-1 #first make all terms even
count=count+1
for i in range(n):
arr[i]=arr[i]//2 #then take half
count=count+1
return count-1
- The number of fruits in each basket needs to be reduced to zero.
- In order to reduce each basket by one and increase the count after each reduction operation, we would first identify the baskets containing odd fruits.
- Then, in a single operation, we will take half of all of these basket fruits.
- This will continue until there are no fruits left in any baskets.
- In the end, I returned count-1 because the count was increased by one at the last step even though all baskets had no fruits.
#SPJ2