You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: solution/2200-2299/2240.Number of Ways to Buy Pens and Pencils/README_EN.md
+5-1
Original file line number
Diff line number
Diff line change
@@ -57,7 +57,11 @@ The total number of ways to buy pens and pencils is 5 + 3 + 1 = 9.
57
57
58
58
<!-- solution:start -->
59
59
60
-
### Solution 1
60
+
### Solution 1: Enumeration
61
+
62
+
We can enumerate the number of pens to buy, denoted as $x$. For each $x$, the maximum number of pencils we can buy is $\frac{\textit{total} - x \times \textit{cost1}}{\textit{cost2}}$. The number of ways for each $x$ is this value plus 1. We sum up the number of ways for all $x$ to get the answer.
63
+
64
+
The time complexity is $O(\frac{\textit{total}}{\textit{cost1}})$, and the space complexity is $O(1)$.
We use an array $d$ to record the denominations of the bills and an array $cnt$ to record the number of bills for each denomination.
88
+
89
+
For the `deposit` operation, we only need to add the number of bills for the corresponding denomination. The time complexity is $O(1)$.
90
+
91
+
For the `withdraw` operation, we enumerate the bills from largest to smallest denomination, taking out as many bills as possible without exceeding the $amount$. Then, we subtract the total value of the withdrawn bills from $amount$. If $amount$ is still greater than $0$ at the end, it means it's not possible to withdraw the $amount$ with the available bills, and we return $-1$. Otherwise, we return the number of bills withdrawn. The time complexity is $O(1)$.
0 commit comments