
Input: ‘N’ = 2, ‘TARGET’ = {2, 3}
Output: 4
In this case, To get the target array from {0, 0}, we first, increment both elements by 1 (2 operations), then double the array (1 operation). Finally, increment the second element (1 more operation).
The first line will contain the integer 'T', the number of test cases.
Each test case consists of two lines.
The first line of input contains one integer, 'N', the length of the ‘TARGET’ array
Followed by a line containing space-separated ‘N’ non-negative integers, denoting the elements of the array.
For each test case, print the minimum number of operations required to get the target array.
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= 'T' <= 10
1 <= 'N' <= 10^5
0 <= ‘TARGET[i]’ <= 10^9
It is guaranteed that sum of ‘N’ over all test cases is <= 10^5
Time Limit: 1 sec
The idea for this approach is to try out every possible sequence of moves to get the ‘TARGET’ array. So at the start, we will have an array filled with zeros, and at each step, we will perform either operation one on any index or operation two on the whole array.
This can be done using recursion as there is a similar sub-problem involved. So the base case for our recursive solution will be to terminate when an index has its value greater than the value of the same index in the ‘TARGET’ array.
Algorithm:
// This Recursive function will try out every possible way to get the ‘TARGET’ array and return the minimum of all possibilities.
Int getMinimum(N, TARGET[], ARR[])
// The function will return the minimum number of operations required to get the desired array.
Int minimumSteps(N, TARGET[])
The idea for this approach is to analyze the ‘TARGET’ array and apply the given operations in reverse order and find if we can make the ‘TARGET’ array equal to all zeros.
So the operations in reverse are now:
So in our solution, we will first find out all odd elements, and if there are any we have to decrement them by one using first reverse operations, as it is not divisible by two and our array with all zeros can never have a state of real value as any of its element, then we divide the whole array by two as all of them are even, we can keep a variable to store the moves performed in a reverse manner and return that as our answer.
Algorithm:
// The function will return the minimum number of operations required to get the desired array.
Int minimumSteps(N, TARGET[])