- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 51 lines of C++ from the credited upstream file maximum-number-of-items-from-sale-ii.cpp.
- The implementation visibly relies on sequence storage, ordered lookup.
- 7 loop blocks detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
123 45class Solution {6public:7 int maximumSaleItems(vector<vector<int>>& items, int budget) {8 static const int NEG_INF = numeric_limits<int>::min();9 10 int max_f = 0;11 for (const auto& x : items) {12 max_f = max(max_f, x[0]);13 }14 vector<int> cnt(max_f + 1);15 for (const auto& x : items) {16 ++cnt[x[0]];17 }18 vector<int> total(size(cnt));19 for (int i = 1; i < size(cnt); ++i) {20 if (!cnt[i]) {21 continue;22 }23 for (int j = i; j < size(cnt); j += i) {24 total[i] += cnt[j];25 }26 }27 int min_p = numeric_limits<int>::max();28 for (const auto& x : items) {29 min_p = min(min_p, x[1]);30 }31 map<int, int64_t> group;32 for (const auto& x : items) {33 if (x[1] >= 2 * min_p) {34 continue;35 }36 group[x[1]] += total[x[0]] - 1;37 }38 int result = 0;39 for (const auto& [p, x] : group) {40 const auto c = min(static_cast<int64_t>(budget) / p, x);41 result += 2 * c;42 budget -= c * p;43 if (budget < p) {44 break;45 }46 }47 result += budget / min_p;48 return result;49 }50};51