【每日一题】买钢笔和铅笔的方案数

Tag

【枚举】【数学】【2023-09-01】


题目来源

2240. 买钢笔和铅笔的方案数在这里插入图片描述

题目解读

现在你有一笔钱 total,用来购买钢笔和铅笔,它们的价格分别为 cost1cost2,试问你可以有多少种不同的购买方案。其中,出现的价格与钱数都是整数,购买笔的数量可以是任意数目(包括 0)。


解题思路

方法一:枚举

我们拥有的这笔钱最多可以买 ⌊ t o t a l c o s t 1 ⌋ \lfloor \frac{total}{cost1} \rfloor cost1total 支钢笔,加上可以买 0 支钢笔,那么我们买钢笔的方案数为 1 + ⌊ t o t a l c o s t 1 ⌋ 1 + \lfloor \frac{total}{cost1} \rfloor 1+cost1total

现在我们枚举可以买的钢笔的数量 i,则 ⌊ t o t a l − i ∗ c o s t 1 c o s t 2 ⌋ \lfloor \frac{total - i*cost1}{cost2} \rfloor cost2totalicost1 表示买了 i 支钢笔的情况下剩下的钱可以买的铅笔的数量,也表示此时的方案数(不包括买 0 支铅笔的情况),那么 1 + ⌊ t o t a l − i ∗ c o s t 1 c o s t 2 ⌋ 1 + \lfloor \frac{total - i*cost1}{cost2} \rfloor 1+cost2totalicost1 则表示买了 i 支钢笔时的方案数(包括买 0 支铅笔的情况),于是总的方案数为:

∑ i = 0 ⌊ t o t a l c o s t 1 ⌋ ( 1 + ⌊ t o t a l − i × c o s t 1 c o s t 2 ⌋ ) \sum_{i=0}^{\lfloor \frac{total}{cost1} \rfloor}{\left( 1+\lfloor \frac{total-i\times cost1}{cost2} \rfloor \right)} i=0cost1total(1+cost2totali×cost1)

实现代码

class Solution {
public:
    long long waysToBuyPensPencils(int total, int cost1, int cost2) {
        long long n = 1 + total / cost1, res = 0;
        for (long long i = 0; i < n; ++i) {
            res += 1 + (total - cost1 * i) / cost2;
        }
        return res;
    }
};

复杂度分析

时间复杂度: O ( ⌊ t o t a l c o s t 1 ⌋ ) O(\lfloor \frac{total}{cost1} \rfloor) O(⌊cost1total⌋)

空间复杂度: O ( 1 ) O(1) O(1)


写在最后

以上就是本篇文章的内容了,感谢您的阅读。🍗🍗🍗

如果感到有所收获的话可以给博主点一个 👍 哦。

如果文章内容有任何错误或者您对文章有任何疑问,欢迎私信博主或者在评论区指出。💬💬💬

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wang_nn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值