Find the Minimum Number of Fibonacci Numbers Whose Sum Is K — LeetCode 1414 Python Solution
- Problem
- #1414
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- k = 7
- Output
- 2
- Explanation
- The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
Python solution
class Solution:
def findMinFibonacciNumbers(self, k: int) -> int:
a = b = 1
while b <= k:
a, b = b, a + b
ans = 0
while k:
if k >= b:
k -= b
ans += 1
a, b = b - a, a
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(\log k) |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K?
- LeetCode 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K?
- The Python solution on this page runs in O(\log k).
- What is the space complexity of LeetCode 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K cover?
- LeetCode 1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K is tagged Greedy and Math on LeetCode.