2240. Number of Ways to Buy Pens and Pencils Medium
1/**
2 * [2240] Number of Ways to Buy Pens and Pencils
3 *
4 * 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.
5 * Return the number of distinct ways you can buy some number of pens and pencils.
6 *
7 * Example 1:
8 *
9 * Input: total = 20, cost1 = 10, cost2 = 5
10 * Output: 9
11 * Explanation: The price of a pen is 10 and the price of a pencil is 5.
12 * - If you buy 0 pens, you can buy 0, 1, 2, 3, or 4 pencils.
13 * - If you buy 1 pen, you can buy 0, 1, or 2 pencils.
14 * - If you buy 2 pens, you cannot buy any pencils.
15 * The total number of ways to buy pens and pencils is 5 + 3 + 1 = 9.
16 *
17 * Example 2:
18 *
19 * Input: total = 5, cost1 = 10, cost2 = 10
20 * Output: 1
21 * Explanation: The price of both pens and pencils are 10, which cost more than total, so you cannot buy any writing utensils. Therefore, there is only 1 way: buy 0 pens and 0 pencils.
22 *
23 *
24 * Constraints:
25 *
26 * 1 <= total, cost1, cost2 <= 10^6
27 *
28 */
29pub struct Solution {}
30
31// problem: https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/
32// discuss: https://leetcode.com/problems/number-of-ways-to-buy-pens-and-pencils/discuss/?currentPage=1&orderBy=most_votes&query=
33
34// submission codes start here
35
36impl Solution {
37 pub fn ways_to_buy_pens_pencils(total: i32, cost1: i32, cost2: i32) -> i64 {
38 let mut result = 0i64;
39 for i in 0..total / cost1 + 1 {
40 result += ((total - i * cost1) / cost2) as i64 + 1;
41 }
42
43 result
44 }
45}
46
47// submission codes end
48
49#[cfg(test)]
50mod tests {
51 use super::*;
52
53 #[test]
54 fn test_2240() {
55 assert_eq!(Solution::ways_to_buy_pens_pencils(20, 10, 5), 9);
56 }
57}
58
Back
© 2025 bowen.ge All Rights Reserved.