Find the Minimum Number of Fibonacci Numbers Whose Sum Is K
Description
Given the number k
, return the minimum number of Fibonacci numbers whose sum is equal to k
, whether a Fibonacci number could be used multiple times.
The Fibonacci numbers are defined as:
- F1 = 1
- F2 = 1
- Fn = Fn-1 + Fn-2 , for n > 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 <= 10^9
Solution(javascript)
/**
* @param {number} k
* @return {number}
*/
const findMinFibonacciNumbers = function (k) {
const sequence = [1, 1]
let a = 1
let b = 1
while (b <= k) {
const next = a + b
a = b
b = next
sequence.push(next)
}
const search = (target) => {
let left = 0
let right = sequence.length - 1
let result = -1
while (left <= right) {
const middle = Math.floor(left + (right - left) / 2)
const num = sequence[middle]
if (num === target) {
return num
} if (num < target) {
result = num
left = middle + 1
} else {
right = middle - 1
}
}
return result
}
let count = 1
while (search(k) < k) {
count += 1
k -= search(k)
}
return count
}