Given an array arr[] of size N, the task is to find the minimum cost required for converting all the elements into a Fibonacci number.
For converting an integer a to an interger b the cost is given as | a – b |.
Examples :
Input : { 56, 34, 23, 98, 7 }
Output : 13
Explanation :
arr[0] = 56 --> Converted to 55 --> cost is 1
arr[1] = 34 --> Converted to 34 --> cost is 0
arr[2] = 23 --> Converted to 21 --> cost is 2
arr[3] = 98 --> Converted to 89 --> cost is 9
arr[4] = 7 --> Converted to 8 --> cost is 1
Input : { 543, 32, 7, 23, 641 }
Output : 103
Approach :
The idea is to find the nearest Fibonacci number for each element to minimize the cost:
- Traverse the array from left to right.
- The Nth Fibonacci number is given by, fn = (an – bn )/51/2 ,where a = (1+51/2)/2 and b = (1-51/2)/2.
- From this formula, if fn is given we can derive n = floor[ log(51/2*fn) / log(a) ].
- For every element, we find n using the above equation and then compute the nth and (n+1)th Fibonacci number and take the one closest to the element.
- We add the absolute difference of the element and the nearest Fibonacci number to our cost.
Implementation :
# Python implementation
import math
# Get Nth fibonacci
def nthFibo(n):
a = (5**(1/2)+1)/2
b = (-5**(1/2)+1)/2
r = 5**(1/2)
# Getting the Nth fibonacci
ans = (a**n - b**n)/r
return int(ans)
# Function to find the
# nearest fibonacci number
def nearFibo(fn):
a = (5**(1/2)+1)/2
# Getting n for given fn
n = int( math.log((5**(1/2))*fn) / math.log(a) )
nth = nthFibo(n)
nplus = nthFibo(n+1)
# Returning the nearest fibonacci
if abs(fn-nth) < abs(fn-nplus):
return nth
else:
return nplus
# Function to get the greatest
# fibonacci lesser than maximum element
def getCost(arr):
cost = 0
# Traversing the array
for i in arr:
# Getting the nearest Fibonacci number
fibo = nearFibo(i)
cost += abs(i-fibo)
return cost
# Driver Code
arr = [56, 34, 23, 98, 7]
# Function call
ans = getCost(arr)
# To display the result
print(ans)
Time Complexity : O(N)
Auxiliary Space : O(1)