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: 7
💡 Note: 0 pens: can buy 0,1,2 pencils (3 ways). 1 pen ($4 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 Pencils INPUT $20 Total Money Pen: $1 Pencil: $1 total 20 cost1 1 cost2 1 Find all ways to spend ALGORITHM STEPS 1 Initialize count = 0 Track total combinations 2 Loop: pens = 0 to 20 Try each pen quantity 3 Calc remaining money remain = total - pens*cost1 4 Add pencil options count += remain/cost2 + 1 for pens in 0..20: remain = 20 - pens*1 pencils = 0 to remain count += remain + 1 FINAL RESULT Total Ways 231 Sample Combinations: pens=0: 21 ways (0-20 pencils) pens=1: 20 ways (0-19 pencils) pens=2: 19 ways (0-18 pencils) ... pens=20: 1 way (0 pencils) Sum: 21+20+...+1 = 231 Output: 231 OK - All combinations counted Key Insight: For each number of pens bought, calculate remaining money and count all possible pencil quantities. If remaining = R, we can buy 0, 1, 2, ... R/cost2 pencils, giving (R/cost2 + 1) options per pen count. Single loop O(total/cost1) instead of nested O(total^2) -- much faster for large inputs! TutorialsPoint - Number of Ways to Buy Pens and Pencils | Optimized Single Loop Approach
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