Problem Description
You are given an integer total indicating the amount of money you have, along with two integers cost1 and cost2 representing the price of a pen and pencil respectively. You can choose to buy any number (including zero) of pens and pencils as long as you do not exceed the total money available. The task is to determine the number of distinct ways to spend your money on pens and pencils.
Key Insights
- Iterate over the possible number of pens that can be bought (from 0 up to total / cost1).
- For each fixed number of pens, compute the remaining money.
- Calculate the number of pencils that can be bought with the remaining money as (remaining / cost2) + 1 (including buying zero pencils).
- The sum of possibilities for each number of pens gives the final answer.
Space and Time Complexity
Time Complexity: O(total / cost1)
Space Complexity: O(1)
Solution
We use a simple iterative approach. The main idea is to loop through how many pens you can buy within the total budget. For each possibility, calculate the remaining money and determine how many ways you can spend that remaining amount on pencils. Adding 1 accounts for the possibility of buying zero pencils. This enumeration avoids any nested loops over both items and efficiently calculates the answer using arithmetic operations.