- Define precisely what one DP state represents.
- Establish the base cases before transitions are evaluated.
- Process states in dependency order and combine only already-known values.
Code notes
- 96 lines of C++ from the credited upstream file maximum-number-of-items-from-sale-i.cpp.
- The implementation visibly relies on sequence storage, cached states.
- 15 loop blocks detected.
Complexity
Multiply the number of reachable states by the work performed for each transition, then include the stored state table in memory usage.
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 vector<int> dp(budget + 1, NEG_INF);28 dp[0] = 0;29 for (const auto& x : items) {30 for (int i = size(dp) - 1; i - x[1] >= 0; --i) {31 if (dp[i - x[1]] == NEG_INF) {32 continue;33 }34 dp[i] = max(dp[i], dp[i - x[1]] + total[x[0]]);35 }36 }37 int min_p = numeric_limits<int>::max();38 for (const auto& x : items) {39 min_p = min(min_p, x[1]);40 }41 int result = 0;42 for (int i = 0; i < size(dp); ++i) {43 if (dp[i] == NEG_INF) {44 continue;45 }46 result = max(result, dp[i] + (budget - i) / min_p);47 }48 return result;49 }50};51 52535455class Solution2 {56public:57 int maximumSaleItems(vector<vector<int>>& items, int budget) {58 static const int NEG_INF = numeric_limits<int>::min();59 60 int max_f = 0;61 for (const auto& x : items) {62 max_f = max(max_f, x[0]);63 }64 vector<int> cnt(max_f + 1);65 for (const auto& x : items) {66 ++cnt[x[0]];67 }68 vector<int> total(size(cnt));69 for (int i = 1; i < size(cnt); ++i) {70 if (!cnt[i]) {71 continue;72 }73 for (int j = i; j < size(cnt); j += i) {74 total[i] += cnt[j];75 }76 }77 vector<int> dp(budget + 1, NEG_INF);78 dp[0] = 0;79 for (const auto& x : items) {80 for (int i = size(dp) - 1; i - x[1] >= 0; --i) {81 if (dp[i - x[1]] == NEG_INF) {82 continue;83 }84 dp[i] = max(dp[i], dp[i - x[1]] + total[x[0]]);85 }86 for (int i = x[1]; i < size(dp); ++i) {87 if (dp[i - x[1]] == NEG_INF) {88 continue;89 }90 dp[i] = max(dp[i], dp[i - x[1]] + 1);91 }92 }93 return ranges::max(dp);94 }95};96