Two integer operations are defined as:
ADD_1: Increment the integer by 1MULTIPLY_2: Multiply the integer by 2
Given an integer value k, determine the minimum number of operations it takes to get from 0 to k using the two operations specified above.
Example
kValues[i] = 8
Starting from 0, add 1, then multiply by 2 three times. It takes a minimum of 4 operations to get to 8, so store 4 in index 0 of the return array.
Function Description
Complete the function getMinOperations in the editor.
getMinOperations has the following parameter(s):
kValues[n]: the given k values
Returns:
int[n]: answers to a list of queries in the given order
Sample Input
n = 2
kValues = [5, 3]
Sample Output
4
3
Explanation
0. To get from 0 to kValues[0] = 5, ADD_1 -> MULTIPLY_2 -> MULTIPLY_2 -> ADD_1 to get 0 -> 1 -> 2 -> 4 -> 5. Because it took four operations, store 4 in index 0 of the return array.
1. To get from 0 to kValues[1] = 3, ADD_1 -> MULTIPLY_2 -> ADD_1 to get 0 -> 1 -> 2 -> 3. Because it took three operations, store 3 in index 1 of the return array.
Return the array [4, 3] as the answer.
This Salesforce VO question asks for the minimum number of steps to reach each target value from 0 using only +1 and ×2 operations. The efficient approach is to work backward from k: divide by 2 when the number is even, otherwise subtract 1, until reaching 0. This gives the optimal operation count for each query, and the sample [5, 3] returns [4, 3].