#1414
Find the Minimum Number of Fibonacci Numbers Whose Sum Is K
MediumMathGreedyGreedyDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal 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- 1Step 1: Generate all Fibonacci numbers up to k.
- 2Step 2: Initialize a count to 0 and iterate while k > 0.
- 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.