[LeetCode] Find the Minimum Number of Fibonacci Numbers Whose Sum Is K

1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K

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 for n > 2.

It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int findMinFibonacciNumbers(int k) {
vector<long long> fibo{1,1};
while(fibo.back() < k) fibo.push_back(fibo[fibo.size() - 1] + fibo[fibo.size() - 2]);
int res = 0, i = fibo.size() - 1;
while(i and k) {
if(k >= fibo[i]) {
res++;
k -= fibo[i];
}
i--;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/08/PS/LeetCode/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.