力扣3026.最大好子数组和
题目解析及思路
题目要求找到一个最大的子数组和,并要求子数组中最后一项和第一项相差k,即|nums[i] - nums[j]| == k
求和用前缀和
用哈希表映射,每一个元素对应一个最多包含到它的前缀和
之后找x + k和x - k存不存在,更新答案
同样的元素只保留前缀和小的那项
- 一次遍历
- 求前缀和的同时 哈希表key为元素值 value为前缀和
- 始终保证cnt[key]的前缀和最小
代码
class Solution {
public:
long long maximumSubarraySum(vector<int>& nums, int k) {
long long res = LLONG_MIN , sum = 0;
unordered_map<int,long long> min_s;
for(int x : nums)
{
//找x + k的位置
auto it = min_s.find(x + k);
if(it != min_s.end())
res = max(res,sum + x - it->second);
//找x - k的位置
it = min_s.find(x - k);
if(it != min_s.end())
res = max(res,sum + x - it->second);
//找x的位置
it = min_s.find(x);
if(it == min_s.end() || sum < it->second)
min_s[x] = sum;
//求当前遍历过元素的和
sum += x;
}
return res == LLONG_MIN ? 0 : res;
}
};

661

被折叠的 条评论
为什么被折叠?



