返回介绍

solution / 1500-1599 / 1553.Minimum Number of Days to Eat N Oranges / README_EN

发布于 2024-06-17 01:03:18 字数 3398 浏览 0 评论 0 收藏 0

1553. Minimum Number of Days to Eat N Oranges

中文文档

Description

There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:

  • Eat one orange.
  • If the number of remaining oranges n is divisible by 2 then you can eat n / 2 oranges.
  • If the number of remaining oranges n is divisible by 3 then you can eat 2 * (n / 3) oranges.

You can only choose one of the actions per day.

Given the integer n, return _the minimum number of days to eat_ n _oranges_.

 

Example 1:

Input: n = 10
Output: 4
Explanation: You have 10 oranges.
Day 1: Eat 1 orange,  10 - 1 = 9.  
Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)
Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. 
Day 4: Eat the last orange  1 - 1  = 0.
You need at least 4 days to eat the 10 oranges.

Example 2:

Input: n = 6
Output: 3
Explanation: You have 6 oranges.
Day 1: Eat 3 oranges, 6 - 6/2 = 6 - 3 = 3. (Since 6 is divisible by 2).
Day 2: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. (Since 3 is divisible by 3)
Day 3: Eat the last orange  1 - 1  = 0.
You need at least 3 days to eat the 6 oranges.

 

Constraints:

  • 1 <= n <= 2 * 109

Solutions

Solution 1

class Solution:
  def minDays(self, n: int) -> int:
    @cache
    def dfs(n):
      if n < 2:
        return n
      return 1 + min(n % 2 + dfs(n // 2), n % 3 + dfs(n // 3))

    return dfs(n)
class Solution {
  private Map<Integer, Integer> f = new HashMap<>();

  public int minDays(int n) {
    return dfs(n);
  }

  private int dfs(int n) {
    if (n < 2) {
      return n;
    }
    if (f.containsKey(n)) {
      return f.get(n);
    }
    int res = 1 + Math.min(n % 2 + dfs(n / 2), n % 3 + dfs(n / 3));
    f.put(n, res);
    return res;
  }
}
class Solution {
public:
  unordered_map<int, int> f;

  int minDays(int n) {
    return dfs(n);
  }

  int dfs(int n) {
    if (n < 2) return n;
    if (f.count(n)) return f[n];
    int res = 1 + min(n % 2 + dfs(n / 2), n % 3 + dfs(n / 3));
    f[n] = res;
    return res;
  }
};
func minDays(n int) int {
  f := map[int]int{0: 0, 1: 1}
  var dfs func(int) int
  dfs = func(n int) int {
    if v, ok := f[n]; ok {
      return v
    }
    res := 1 + min(n%2+dfs(n/2), n%3+dfs(n/3))
    f[n] = res
    return res
  }
  return dfs(n)
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文