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 thenumber of distinct ways you can buy some number of pens and pencils.
Input: total =20, cost1 =10, cost2 =5Output: 9Explanation: The price of a pen is10 and the price of a pencil is5.- If you buy 0 pens, you can buy 0,1,2,3, or 4 pencils.- If you buy 1 pen, you can buy 0,1, or 2 pencils.- If you buy 2 pens, you cannot buy any pencils.The total number of ways to buy pens and pencils is5+3+1=9.
Input: total =5, cost1 =10, cost2 =10Output: 1Explanation: 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.
For each possible number of pens you can buy (from 0 up to total // cost1), calculate how many pencils you can buy with the remaining money. Sum over all possibilities.
classSolution {
public:longlong waysToBuyPensPencils(longlong total, longlong cost1, longlong cost2) {
longlong ans =0;
for (longlong x =0; x * cost1 <= total; ++x) {
longlong rem = total - x * cost1;
ans += rem / cost2 +1;
}
return ans;
}
};
classSolution {
publiclongwaysToBuyPensPencils(long total, long cost1, long cost2) {
long ans = 0;
for (long x = 0; x * cost1 <= total; x++) {
long rem = total - x * cost1;
ans += rem / cost2 + 1;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funwaysToBuyPensPencils(total: Long, cost1: Long, cost2: Long): Long {
var ans = 0Lvar x = 0Lwhile (x * cost1 <= total) {
val rem = total - x * cost1
ans += rem / cost2 + 1 x++ }
return ans
}
}
1
2
3
4
5
6
7
8
9
classSolution:
defwaysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
ans =0 x =0while x * cost1 <= total:
rem = total - x * cost1
ans += rem // cost2 +1 x +=1return ans
1
2
3
4
5
6
7
8
9
10
11
12
impl Solution {
pubfnways_to_buy_pens_pencils(total: i64, cost1: i64, cost2: i64) -> i64 {
letmut ans =0;
letmut x =0;
while x * cost1 <= total {
let rem = total - x * cost1;
ans += rem / cost2 +1;
x +=1;
}
ans
}
}