![]() |
VOOZH | about |
Given an array arr[] consisting of N integers, the task is to minimize the cost of converting all array elements to a Fibonacci Number, where the cost of converting a number A to B is the absolute difference between A and B.
Examples:
Input: arr[] = {56, 34, 23, 98, 7}
Output: 13
Explanation:
Following are the conversion of elements required to make all array elements as Fibonacci Numbers:
- Convert arr[0](= 56) to 55. Cost = | 56 - 55| = 1.
- Convert arr[1](= 34) to 34. Cost = |34 - 34| = 0.
- Convert arr[2](= 23) to 21. Cost = |23 - 21| = 2.
- Convert arr[3](= 98) to 89. Cost = |98 - 89| = 9.
- Convert arr[4](= 7) to 8. Cost = |7 - 8| = 1.
Therefore, the total cost of changing all array elements to Fibonacci numbers = 1 + 0 + 2 + 9 + 1 = 13.
Input: {543, 32, 7, 23, 641}
Output: 103
Approach: The given problem can be solved by replacing each array element with its nearest Fibonacci Number to get the minimum cost for changing all array elements to Fibonacci Number. Follow the step below to solve the given problem:
Below is the implementation of the above approach:
13
Time Complexity: O(N)
Auxiliary Space: O(1), since no extra space has been taken.