Most Expensive Item That Can Not Be Bought - Problem

You are given two distinct prime numbers primeOne and primeTwo. Alice and Bob are visiting a market. The market has an infinite number of items, for any positive integer x there exists an item whose price is x.

Alice wants to buy some items from the market to gift to Bob. She has an infinite number of coins in the denomination primeOne and primeTwo. She wants to know the most expensive item she can not buy to gift to Bob.

Return the price of the most expensive item which Alice can not gift to Bob.

Input & Output

Example 1 — Small Primes
$ Input: primeOne = 3, primeTwo = 5
Output: 7
💡 Note: Numbers that can't be made: 1, 2, 4, 7. We can make 3(1×3), 5(1×5), 6(2×3), 8(1×3+1×5), 9(3×3), 10(2×5), 11(2×3+1×5), etc. The largest impossible is 7.
Example 2 — Larger Primes
$ Input: primeOne = 2, primeTwo = 3
Output: 1
💡 Note: With coins 2 and 3, we can make: 2, 3, 4(2+2), 5(2+3), 6(3+3), 7(2+2+3), etc. Only 1 cannot be made.
Example 3 — Edge Case
$ Input: primeOne = 7, primeTwo = 11
Output: 59
💡 Note: Using formula: 7×11 - 7 - 11 = 77 - 18 = 59. The largest number that cannot be represented as a combination of 7 and 11 is 59.

Constraints

  • 2 ≤ primeOne, primeTwo ≤ 104
  • primeOne and primeTwo are distinct prime numbers

Visualization

Tap to expand
Most Expensive Item That Can Not Be Bought INPUT Market Items (Infinite) 1 2 3 4 5 ... Alice's Coins 3 5 Input Values: primeOne = 3 primeTwo = 5 ALGORITHM STEPS 1 Frobenius Number For coprime a,b: F(a,b) = a*b - a - b 2 Check Coprimality 3 and 5 are coprime (GCD = 1) 3 Apply Formula F = 3*5 - 3 - 5 F = 15 - 3 - 5 4 Calculate Result F = 7 Verification: 6 = 3+3 [OK] 8 = 3+5 [OK] 9 = 3+3+3 [OK] 7 = ? [IMPOSSIBLE] 10 = 5+5 [OK] 11 = 3+3+5 [OK] FINAL RESULT Most Expensive Unbuyable Item 7 Alice cannot buy a gift worth exactly 7 coins Output: 7 Key Insight: The Frobenius Number (or Chicken McNugget Theorem) states that for two coprime positive integers a and b, the greatest number that cannot be expressed as a*x + b*y (where x,y are non-negative) is: a*b - a - b. Since primes are always coprime to each other, this formula directly applies. Time: O(1), Space: O(1). TutorialsPoint - Most Expensive Item That Can Not Be Bought | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
8.5K Views
Medium Frequency
~15 min Avg. Time
245 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