Number of Ways to Buy Pens and Pencils - 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.

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.

Input & Output

Example 1 — Basic Case
$ Input: total = 20, cost1 = 1, cost2 = 1
Output: 231
💡 Note: With $20 and both items costing $1, we can buy 0-20 pens and 0-20 pencils. For 0 pens: 21 pencil options (0-20). For 1 pen: 20 pencil options (0-19). Pattern continues: 21+20+19+...+1 = 231 ways.
Example 2 — Different Costs
$ Input: total = 5, cost1 = 10, cost2 = 10
Output: 1
💡 Note: Budget is $5 but both items cost $10. Can only afford 0 pens and 0 pencils, so there's only 1 way: buy nothing.
Example 3 — Unequal Costs
$ Input: total = 6, cost1 = 2, cost2 = 3
Output: 9
💡 Note: 0 pens: can buy 0,1,2 pencils (3 ways). 1 pen ($2 left): can buy 0,1 pencils (2 ways). 2 pens ($2 left): can buy 0 pencils (1 way). 3 pens ($0 left): can buy 0 pencils (1 way). Total: 3+2+1+1 = 7 ways.

Constraints

  • 1 ≤ total, cost1, cost2 ≤ 106

Visualization

Tap to expand
Number of Ways to Buy Pens and PencilsInputBudget: $20Pen cost: $1Pencil cost: $1Find All Combinations0 pens: 21 pencil options (0-20)1 pen: 20 pencil options (0-19)2 pens: 19 pencil options (0-18)...Output231 waysTotal combinationsKey insight: Fix one item quantity, calculate the other mathematicallyOptimal: O(total) time, O(1) space
Understanding the Visualization
1
Input
Budget and item costs
2
Process
Find all valid pen-pencil combinations
3
Output
Total number of distinct ways
Key Takeaway
🎯 Key Insight: Instead of checking every combination, fix the pen quantity and use division to count pencil options instantly
Asked in
Microsoft 15 Amazon 12
25.0K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen