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 = 1
F2 = 1
Fn = Fn-1 + Fn-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 <= 109
Solutions
Solution 1: Greedy
We can greedily select the largest Fibonacci number that does not exceed \(k\) each time, then subtract this number from \(k\) and increment the answer by one. This process is repeated until \(k = 0\).
Since we greedily select the largest Fibonacci number that does not exceed \(k\) each time, suppose this number is \(b\), the previous number is \(a\), and the next number is \(c\). Subtracting \(b\) from \(k\) results in a value that is less than \(a\), which means that after selecting \(b\), we will not select \(a\). This is because if we could select \(a\), then we could have greedily selected the next Fibonacci number \(c\) instead of \(b\) earlier, which contradicts our assumption. Therefore, after selecting \(b\), we can greedily reduce the Fibonacci number.
The time complexity is \(O(\log k)\), and the space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
|