![]() |
VOOZH | about |
Given a sequence of N elements, only three operations can be performed on any element at most one time. The operations are:
Perform any one of the operations on all elements in the array. The task is to find the minimum number of operations(addition and subtraction) that can be performed on the sequence, in order to convert it into a Geometric Progression. If it is not possible to generate a GP by performing the above operations, print -1.
Examples:
Input: a[] = {1, 1, 4, 7, 15, 33}
Output: The minimum number of operations are 4.
Steps:
- Keep a1 unchanged
- Add one to a2.
- Keep a3 unchanged
- Subtract one from a4.
- Subtract one from a5.
- Add one to a6.
The resultant sequence is {1, 2, 4, 8, 16, 32}
Input: a[] = {20, 15, 20, 15}
Output: -1
Approach The key observation to be made here is that any Geometric Progression is uniquely determined by only its first two elements (Since the ratio between each of the next pairs has to be the same as the ratio between this pair, consisting of the first two elements). Since only 3*3 permutations are possible. The possible combination of operations are (+1, +1), (+1, 0), (+1, -1), (-1, +1), (-1, 0), (-1, -1), (0, +1), (0, 0) and (0, -1). Using brute force all these 9 permutations and checking if they form a GP in linear time will give us the answer. The minimum of the operations which result in combinations which are in GP will be the answer.
Below is the implementation of the above approach:
Minimum Number of Operations are 2 The resultant sequence is: 8 20 50 125
Time Complexity : O(9*N)
Space Complexity: O(1)