卖,那么遍历所有 end}_j=i 的购买请求,有 f[i+1] = \max (f[\textit{start}_j]+\textit{gold}_j)。为了方便遍历,可以先把所有 end 相同的数据用哈希表归类。
两种情况取最大值。
初始值 f[0]=0。
最终答案为 f[n]。
[sol-Python3]
1 2 3 4 5 6 7 8 9 10 11
classSolution: defmaximizeTheProfit(self, n: int, offers: List[List[int]]) -> int: groups = [[] for _ inrange(n)] for start, end, gold in offers: groups[end].append((start, gold)) f = [0] * (n + 1) for end, g inenumerate(groups): f[end + 1] = f[end] for start, gold in g: f[end + 1] = max(f[end + 1], f[start] + gold) return f[n]
[sol-Java]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { publicintmaximizeTheProfit(int n, List<List<Integer>> offers) { List<int[]>[] groups = newArrayList[n]; Arrays.setAll(groups, e -> newArrayList<>()); for (var offer : offers) groups[offer.get(1)].add(newint[]{offer.get(0), offer.get(2)});
varf=newint[n + 1]; for (intend=0; end < n; end++) { f[end + 1] = f[end]; for (var p : groups[end]) f[end + 1] = Math.max(f[end + 1], f[p[0]] + p[1]); } return f[n]; } }
[sol-C++]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: intmaximizeTheProfit(int n, vector<vector<int>> &offers){ vector<vector<pair<int, int>>> groups(n); for (auto &offer: offers) groups[offer[1]].emplace_back(offer[0], offer[2]);
vector<int> f(n + 1); for (int end = 0; end < n; end++) { f[end + 1] = f[end]; for (auto &[start, gold]: groups[end]) f[end + 1] = max(f[end + 1], f[start] + gold); } return f[n]; } };
[sol-Go]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
funcmaximizeTheProfit(n int, offers [][]int)int { type pair struct{ start, gold int } groups := make([][]pair, n) for _, offer := range offers { start, end, gold := offer[0], offer[1], offer[2] groups[end] = append(groups[end], pair{start, gold}) }
f := make([]int, n+1) for end, g := range groups { f[end+1] = f[end] for _, p := range g { f[end+1] = max(f[end+1], f[p.start]+p.gold) } } return f[n] }
funcmax(a, b int)int { if b > a { return b }; return a }