1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K
Description
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:
F1 = 1F2 = 1Fn = Fn-1 + Fn-2forn > 2.
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 <= 109
Solutions
Solution: Iteration
- Time complexity: O(logk)
- Space complexity: O(logk)
JavaScript
js
/**
* @param {number} k
* @return {number}
*/
const findMinFibonacciNumbers = function (k) {
const fibonacciDp = [0, 1, 1];
const fibonacci = n => (fibonacciDp[n] = fibonacciDp[n - 1] + fibonacciDp[n - 2]);
let current = 3;
let result = 0;
while (fibonacciDp.at(-1) < k) {
fibonacci(current++);
}
for (let index = fibonacciDp.length - 1; index > 0; index--) {
const value = fibonacciDp[index];
if (k < value) continue;
k -= value;
result += 1;
if (k === 0) return result;
}
return result;
};