Number of Ways to Buy Pens and Pencils — LeetCode 2240 Python Solution

MediumMathEnumeration
Problem
#2240
Reading time
2 min

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

Python
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 ans

Complexity

MeasureComplexity
TimeO(\frac{\textit{total}}{\textit{cost1}})
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview