LeetCode 2382. 删除操作后的最大子段和
倒叙 + 并查集
typedef long long LL;
class Solution {
public:
vector<long long> maximumSegmentSum(vector<int>& nums, vector<int>& removeQueries) {
int n = nums.size();
vector<int> p(n + 1);
vector<LL> s(n + 1);
for(int i = 0; i < n; i ++)
p[i] = i, s[i] = 0;
function<int(int)> find = [&](int x) -> int{
if(p[x] != x) p[x] = find(p[x]);
return p[x];
};
vector<LL> res;
LL maxs = 0;
for(int i = removeQueries.size() - 1; i >= 0; i --)
{
int x = removeQueries[i];
s[x] = nums[x];
for(int j = x - 1; j <= x + 1; j += 2)
{
if(j >= 0 && j < n && s[j] > 0)
s[x] += s[find(j)], p[find(j)] = x;
}
res.push_back(maxs);
maxs = max(maxs, s[x]);
}
reverse(res.begin(), res.end());
return res;
}
};