#1414

Find the Minimum Number of Fibonacci Numbers Whose Sum Is K

Medium
MathGreedyGreedyDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach uses a greedy strategy. By always choosing the largest Fibonacci number that is less than or equal to the remaining value of k, we can minimize the number of Fibonacci numbers needed to reach k.

⚙️

Algorithm

3 steps
  1. 1Step 1: Generate all Fibonacci numbers up to k.
  2. 2Step 2: Initialize a count to 0 and iterate while k > 0.
  3. 3Step 3: For each iteration, find the largest Fibonacci number less than or equal to k, subtract it from k, and increment the count.
solution.py15 lines
1# Full working Python code
2
3def findMinFibonacciNumbers(k):
4    fib = [1, 1]
5    while fib[-1] <= k:
6        fib.append(fib[-1] + fib[-2])
7    count = 0
8    while k > 0:
9        for i in range(len(fib) - 1, -1, -1):
10            if fib[i] <= k:
11                k -= fib[i]
12                count += 1
13                break
14    return count
15

Complexity note: The time complexity is O(n) because we are generating Fibonacci numbers up to k, and the while loop runs until k becomes 0, which is efficient due to the greedy approach.

  • 1Greedy algorithms often yield optimal solutions for problems involving sums.
  • 2Understanding Fibonacci sequences can help in recognizing patterns in number combinations.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.