目标
给你五个整数 cost1, cost2, costBoth, need1 和 need2。
有三种类型的物品可以购买:
- 类型 1 的物品花费 cost1,并仅满足类型 1 的需求 1 个单位。
- 类型 2 的物品花费 cost2,并仅满足类型 2 的需求 1 个单位。
- 类型 3 的物品花费 costBoth,同时满足类型 1 和类型 2 的需求各 1 个单位。
你需要购买足够的物品,使得:
- 满足类型 1 的总需求 至少 为 need1。
- 满足类型 2 的总需求 至少 为 need2。
返回满足这些需求的 最小 可能总花费。
示例 1:
输入: cost1 = 3, cost2 = 2, costBoth = 1, need1 = 3, need2 = 2
输出: 3
解释:
购买 3 个类型 3 的物品,总花费为 3 * 1 = 3,此时类型 1 的总需求满足 3(>= need1 = 3),类型 2 的总需求满足 3(>= need2 = 2)。
任何其他有效的购买方案都会花费更多,因此最小总花费为 3。
示例 2:
输入: cost1 = 5, cost2 = 4, costBoth = 15, need1 = 2, need2 = 3
输出: 22
解释:
购买 need1 = 2 个类型 1 的物品和 need2 = 3 个类型 2 的物品,总花费为 2 * 5 + 3 * 4 = 10 + 12 = 22。
任何其他有效的购买方案都会花费更多,因此最小总花费为 22。
示例 3:
输入: cost1 = 5, cost2 = 4, costBoth = 15, need1 = 0, need2 = 0
输出: 0
解释:
由于不需要任何物品(need1 = need2 = 0),因此无需购买,总花费为 0。
说明:
- 1 <= cost1, cost2, costBoth <= 10^6
- 0 <= need1, need2 <= 10^9
思路
需要采购类型1的物品 need1 个,类型2的物品 need2 个。单独购买类型1的价格是 cost1,单独购买类型2的价格是 cost2,类型1与类型2一起买的价格是 costBoth。返回满足需求的最小花费。
分类讨论:
costBoth <= cost1,cost2,花费为max(need1, need2) * costBothcost1 < costBoth <= cost2,花费为need2 * costBoth + cost1 * max(0, rem1)cost2 < costBoth <= cost1,花费为need1 * costBoth + cost2 * max(0, rem2)cost1,cost2 < costBoth < cost1 + cost2,花费为min(need1, need2) * costBoth + cost2 * max(0, rem2) + cost1 * max(0, rem1)cost1 + cost2 < costBoth, 花费为cost1 * need1 + cost2 * need2
代码
/**
* @date 2026-11-11 8:52
*/
public class MinimumCost3789 {
public long minimumCost(int cost1, int cost2, int costBoth, int need1, int need2) {
if (costBoth <= cost1 && costBoth <= cost2) {
return Math.max(need1, need2) * (long) costBoth;
}
if (cost1 < costBoth && costBoth <= cost2) {
return need2 * (long) costBoth + (long) cost1 * Math.max(0, need1 - need2);
}
if (costBoth <= cost1) {
return need1 * (long) costBoth + (long) cost2 * Math.max(0, need2 - need1);
}
if (costBoth <= cost1 + cost2) {
int min = Math.min(need1, need2);
return min * (long) costBoth + (long) cost2 * Math.max(0, need2 - min) + (long) cost1 * Math.max(0, need1 - min);
}
return (long) cost1 * need1 + (long) cost2 * need2;
}
}
性能
