Find the Minimum Number of Fibonacci Numbers Whose Sum Is K Problem
Description
LeetCode Problem 1414.
Given an integer k, return the minimum number of Fibonacci numbers whose sum is equal to k. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
F_1 = 1F_2 = 1F_n = F_(n-1) + F_(n-2)forn > 2.
It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.
Example 1:
Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.
Example 2:
Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.
Example 3:
Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.
Constraints:
1 <= k <= 10^9
Solution
Approach: Greedy, Largest Fibonacci First
List the Fibonacci numbers up to k (there are only about 45 of them below 10^9). Then repeatedly subtract the largest Fibonacci number that is not more than what is left, counting how many we use, until nothing is left.
Why is taking the largest one always safe? First, some optimal answer uses no Fibonacci number twice and no two neighbors: two neighbors F_(i−1) + F_(i−2) can be replaced by the single F_i, and a pair 2 · F_i by F_(i+1) + F_(i−2), which keeps the count and pushes the numbers up, so this rewriting ends. Second, distinct non-neighboring Fibonacci numbers that are all below F_i add up to at most F_i − 1. So if F_i is the largest Fibonacci number that is at most k, such an optimal answer must contain F_i (without it, it could not reach k, and with anything bigger it would overshoot). Taking F_i and solving for k − F_i is therefore optimal. The remainder is also less than F_(i−1), because k < F_(i+1) = F_i + F_(i−1), so the numbers picked keep getting smaller.
Since the list is sorted, one backward pass does it: go from the largest number down, and subtract each one that still fits.
Complexity: O(log k) time and space, since Fibonacci numbers grow exponentially.
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
fib = [1, 1]
while fib[-1] + fib[-2] <= k:
fib.append(fib[-1] + fib[-2])
ans = 0
for f in reversed(fib): # always take the largest Fibonacci number that still fits
if f <= k:
k -= f
ans += 1
if k == 0:
break
return ans