#3789
Medium Algorithms Minimum cost to acquire required items
Math Greedy
34.8% acceptance
Feb 25, 2026
67
5
You are given five integers cost1, cost2, costBoth, need1, and need2.
There are three types of items available:
An item of type 1 costs cost1 and contributes 1 unit to the type 1 requirement only.
An item of type 2 costs cost2 and contributes 1 unit to the type 2 requirement only.
An item of type 3 costs costBoth and contributes 1 unit to both type 1 and type 2 requirements.
You must collect enough items so that the total contribution toward type 1 is at least need1 and the total contribution toward type 2 is at least need2.
Return an integer representing the minimum possible total cost to achieve these requirements.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn minimum_cost(cost1: i32, cost2: i32, cost_both: i32, need1: i32, need2: i32) -> i64 {
let cost = |b: i64| -> i64 {
b * cost_both as i64
+ (need1 as i64 - b).max(0) * cost1 as i64
+ (need2 as i64 - b).max(0) * cost2 as i64
};
[0i64, need1.min(need2) as i64, need1.max(need2) as i64]
.iter().map(|&b| cost(b)).min().unwrap()
}
}