Number of Ways to Buy Pens and Pencils — LeetCode 2240 Python Solution
- Problem
- #2240
- Pattern
- Math and Number Theory
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- 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.
Python solution
class Solution:
def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int:
ans = 0
for x in range(total // cost1 + 1):
y = (total - (x * cost1)) // cost2 + 1
ans += y
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(\frac{\textit{total}}{\textit{cost1}}) |
| Space | O(1) auxiliary |
Pattern: Math and Number Theory
Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 2240. Number of Ways to Buy Pens and Pencils is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.
The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2240. Number of Ways to Buy Pens and Pencils?
- LeetCode 2240. Number of Ways to Buy Pens and Pencils is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2240. Number of Ways to Buy Pens and Pencils?
- The Python solution on this page runs in O(\frac{\textit{total}}{\textit{cost1}}).
- What is the space complexity of LeetCode 2240. Number of Ways to Buy Pens and Pencils?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2240. Number of Ways to Buy Pens and Pencils cover?
- LeetCode 2240. Number of Ways to Buy Pens and Pencils is tagged Math and Enumeration on LeetCode.