Untitled
unknown
plain_text
8 months ago
1.2 kB
3
Indexable
import java.util.HashMap;
import java.util.Map;
class Solution {
private Map<Integer, Integer> memo = new HashMap<>();
public int minDays(int n) {
if (n <= 1) return n; // Base case: 0 days for 0 oranges, 1 day for 1 orange.
if (memo.containsKey(n)) return memo.get(n);
// Option 1: Eat 1 orange, then solve for (n - 1)
int option1 = 1 + minDays(n - 1);
// Option 2: If divisible by 2, eat n/2 oranges, then solve for (n / 2)
int option2 = Integer.MAX_VALUE;
if (n % 2 == 0) {
option2 = 1 + minDays(n / 2);
}
// Option 3: If divisible by 3, eat 2 * (n / 3) oranges, then solve for (n / 3)
int option3 = Integer.MAX_VALUE;
if (n % 3 == 0) {
option3 = 1 + minDays(n / 3);
}
int days = Math.min(option1, Math.min(option2, option3));
memo.put(n, days);
return days;
}
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.minDays(10)); // Output: 4
System.out.println(solution.minDays(6)); // Output: 3
}
}
Editor is loading...
Leave a Comment