[LeetCode] 2240. Number of Ways to Buy Pens and Pencils

发布时间 2023-09-01 04:43:36作者: CNoodle

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.

Example 1:

Input: total = 20, cost1 = 10, cost2 = 5
Output: 9
Explanation: The price of a pen is 10 and the price of a pencil is 5.
- 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 is 5 + 3 + 1 = 9.

Example 2:

Input: total = 5, cost1 = 10, cost2 = 10
Output: 1
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.

Constraints:

  • 1 <= total, cost1, cost2 <= 106

买钢笔和铅笔的方案数。

给你一个整数 total ,表示你拥有的总钱数。同时给你两个整数 cost1 和 cost2 ,分别表示一支钢笔和一支铅笔的价格。你可以花费你部分或者全部的钱,去买任意数目的两种笔。

请你返回购买钢笔和铅笔的 不同方案数目 。

这是一道数学题。由于可以不需要花费所有的钱,就简单许多。这里如果我们只买钢笔,我们最多能买 n = total / cost1 只钢笔。那么我们就从 0 到 n 开始遍历,设我们买了 i 只钢笔之后,剩下的钱最多能买多少铅笔。

时间 - total / cost1

空间O(1)

Java实现

 1 class Solution {
 2     public long waysToBuyPensPencils(int total, int cost1, int cost2) {
 3         long n = 1 + total / cost1;
 4         long res = n;
 5         for (int i = 0; i < n; i++) {
 6             res += (total - cost1 * i) / cost2;
 7         }
 8         return res;
 9     }
10 }

 

LeetCode 题目总结