#2240
Medium Algorithms Number of ways to buy pens and pencils
Math Enumeration
56.6% acceptance
Feb 25, 2026
478
36
You are given an integer total indicating the amount of money you have. You are also given two integers cost1 and cost2 indicating the price of a pen and pencil respectively. You can spend part or all of your money to buy multiple quantities (or none) of each kind of writing utensil.
Return the number of distinct ways you can buy some number of pens and pencils.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn ways_to_buy_pens_pencils(total: i32, cost1: i32, cost2: i32) -> i64 {
let total = total as i64;
let cost1 = cost1 as i64;
let cost2 = cost2 as i64;
let mut ans = 0i64;
let mut pens = 0i64;
while pens * cost1 <= total {
let remaining = total - pens * cost1;
ans += remaining / cost2 + 1;
pens += 1;
}
ans
}
}