Skip to content

Commit 7df622c

Browse files
authored
Create Find the Minimum Number of Fibonacci Numbers Who Sum is K.py
1 parent fe213bb commit 7df622c

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# https://leetcode.com/problems/find-the-minimum-number-of-fibonacci-numbers-whose-sum-is-k/
2+
3+
class Solution:
4+
5+
def generateFib(self, k):
6+
7+
# OBJECTIVE: Return a list of fibonacci numbers from 1 to k
8+
9+
# Create list
10+
fib = [1, 1]
11+
12+
# Populate list
13+
num = 1
14+
while num < k:
15+
16+
# If the new number is less than or equal to k, update num and add it to list
17+
if fib[-1] + fib[-2] <= k:
18+
num = fib[-1] + fib[-2]
19+
fib.append(num)
20+
21+
# If the new number is greater than k, exit loop
22+
else:
23+
break
24+
25+
return fib
26+
27+
def findK(self, fib, n, target):
28+
29+
# OBJECTIVE: Return index of element that equals or closest to target
30+
31+
# If target is 0, exit function
32+
if target == 0:
33+
return 0
34+
35+
# If target is greater than or equal to fib's last element, return it
36+
if target >= fib[n - 1]:
37+
return n - 1
38+
39+
# Create left and right pointers
40+
leftPtr = 0
41+
rightPtr = n - 1
42+
43+
# Do binary search to find target in fib
44+
while leftPtr < rightPtr:
45+
46+
# Create middle pointer
47+
midPtr = (leftPtr + rightPtr) // 2
48+
49+
# If middle element is greater than target, move rightPtr
50+
if fib[midPtr] > target:
51+
rightPtr = midPtr
52+
53+
# If middle element is less than or equal to target, move leftPtr
54+
else:
55+
leftPtr = midPtr + 1
56+
57+
# Return left pointer
58+
return leftPtr - 1
59+
60+
def findMinFibonacciNumbers(self, k: int) -> int:
61+
62+
# OBJECTIVE: Return the minimum number of fibonacci numbers whose sum is equal to k
63+
64+
# If k equals to 1, return 1.
65+
# NOTE: Added this to avoid O(n) space and run time
66+
if k == 1:
67+
return 1
68+
69+
# Generate a list of fibonacci numbers from 1 to k
70+
fib = self.generateFib(k)
71+
n = len(fib)
72+
73+
# If last element equals to k, return 1
74+
if fib[-1] == k:
75+
return 1
76+
77+
# Create a variable to hold minimum number of fibonacci numbers
78+
minLen = 0
79+
80+
# Get minimum number of fibonacci numbers
81+
while k > 0:
82+
83+
# Find k (or value closest to k) in fib
84+
idx = self.findK(fib, n, k)
85+
86+
# Increment minLen
87+
minLen += 1
88+
89+
# Update k by subtracting idx element from it
90+
k -= fib[idx]
91+
92+
return minLen

0 commit comments

Comments
 (0)