Skip to content

Latest commit

 

History

History
84 lines (68 loc) · 1.8 KB

File metadata and controls

84 lines (68 loc) · 1.8 KB

1414. Find the Minimum Number of Fibonacci Numbers Whose Sum Is K

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.

The Fibonacci numbers are defined as:

  • F1 = 1
  • F2 = 1
  • Fn = Fn-1 + Fn-2 for n > 2.

It is guaranteed that for the given constraints we can always find such Fibonacci numbers that sum up to k.

Example 1:

Input: k = 7
Output: 2
Explanation: The Fibonacci numbers are: 1, 1, 2, 3, 5, 8, 13, ...
For k = 7 we can use 2 + 5 = 7.

Example 2:

Input: k = 10
Output: 2
Explanation: For k = 10 we can use 2 + 8 = 10.

Example 3:

Input: k = 19
Output: 3
Explanation: For k = 19 we can use 1 + 5 + 13 = 19.

Constraints:

  • 1 <= k <= 10^9

Solutions (Ruby)

1. Greedy

# @param {Integer} k
# @return {Integer}
def find_min_fibonacci_numbers(k)
  nums = [1, 1]
  ret = 0

  nums.push(nums[-2] + nums[-1]) while nums[-1] < k

  while k > 0
    nums.pop while nums[-1] > k
    k -= nums[-1]
    ret += 1
  end

  ret
end

Solutions (Rust)

1. Greedy

impl Solution {
    pub fn find_min_fibonacci_numbers(mut k: i32) -> i32 {
        let mut nums = vec![1, 1];
        let mut i = 1;
        let mut ret = 0;

        while nums[i] < k {
            nums.push(nums[i - 1] + nums[i]);
            i += 1;
        }

        while k > 0 {
            while nums[i] > k {
                i -= 1;
            }
            k -= nums[i];
            ret += 1;
        }

        ret
    }
}