#2240

Number of Ways to Buy Pens and Pencils

Medium
MathEnumerationEnumerationDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the idea of fixing the number of pencils and calculating the maximum number of pens that can be bought with the remaining money. This reduces the number of iterations significantly.

⚙️

Algorithm

5 steps
  1. 1Step 1: Initialize a counter for the number of ways.
  2. 2Step 2: Loop through all possible quantities of pencils you can buy (from 0 to total // cost2).
  3. 3Step 3: For each quantity of pencils, calculate the remaining money and determine how many pens can be bought with that money.
  4. 4Step 4: For each valid quantity of pens, increment the counter.
  5. 5Step 5: Return the counter as the result.
solution.py6 lines
1def countWays(total, cost1, cost2):
2    count = 0
3    for pencils in range(total // cost2 + 1):
4        remaining = total - pencils * cost2
5        count += remaining // cost1 + 1
6    return count

Complexity note: The time complexity is O(n) because we only loop through the number of pencils, and for each pencil count, we perform a constant time operation to calculate the number of pens.

  • 1Fixing one variable (pencils or pens) allows for a more efficient calculation of the other.
  • 2Understanding the relationship between total money and the costs of items is crucial for optimizing the solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.