Find the Minimum Number of Fibonacci Numbers Whose Sum Is K — LeetCode 1414 Python Solution

MediumGreedyMath
Problem
#1414
Pattern
Greedy
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(\log k)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview