[LeetCode] Number of Ways to Buy Pens and Pencils

2240. Number of Ways to Buy Pens and Pencils

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.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
long long waysToBuyPensPencils(int total, int cost1, int cost2) {
if(cost1 < cost2) return waysToBuyPensPencils(total, cost2, cost1);
long long res = 0;
for(int i = 0; i * cost1 <= total; i++) {
int rem = total - i * cost1;
res += (rem / cost2) + 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/02/PS/LeetCode/number-of-ways-to-buy-pens-and-pencils/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.