the last one in Weekly Contest 202.
Difficulty : Hard
Related Topics : Dynamic Programming
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.
Return the minimum number of days to eat
n
oranges.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.
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.
Input: n = 1 Output: 1
Input: n = 56 Output: 6
1 <= n <= 2*10^9
- mine
- Java
- Memory Limit Exceeded
//O(N)time //O(N)space public int minDays(int n) { int[] dp = new int[n + 1]; for(int i = 1; i <= n; i++){ dp[i] = dp[i - 1] + 1; if(i % 2 == 0) dp[i] = Math.min(dp[i], dp[i/2] + 1); if(i % 3 == 0) dp[i] = Math.min(dp[i], dp[i/3] + 1); } return dp[n]; }
- Memory Limit Exceeded
- Java
- the most votes
Runtime: 3 ms, faster than 98.84%, Memory Usage: 38.7 MB, less than 82.31% of Java online submissions
// O(N)time // O(N)space Map<Integer, Integer> dp = new HashMap<>(); public int minDays(int n) { if (n <= 1) return n; if (!dp.containsKey(n)) dp.put(n, 1 + Math.min(n % 2 + minDays(n / 2), n % 3 + minDays(n / 3))); return dp.get(n); }