2240. Number of Ways to Buy Pens and Pencils ¶ Time: $O(\frac{\texttt{total}}{\texttt{cost1}})$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12class Solution { public: long long waysToBuyPensPencils(int total, int cost1, int cost2) { long ans = 0; const int maxPen = total / cost1; for (int i = 0; i <= maxPen; ++i) ans += (total - i * cost1) / cost2 + 1; return ans; } }; 1 2 3 4 5 6 7 8 9 10 11class Solution { public long waysToBuyPensPencils(int total, int cost1, int cost2) { long ans = 0; final int maxPen = total / cost1; for (int i = 0; i <= maxPen; ++i) ans += (total - i * cost1) / cost2 + 1; return ans; } } 1 2 3 4 5class Solution: def waysToBuyPensPencils(self, total: int, cost1: int, cost2: int) -> int: maxPen = total // cost1 return sum((total - i * cost1) // cost2 for i in range(maxPen + 1)) + maxPen + 1