跳转至

最大好子数组和⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

前缀和与哈希表:

class Solution {
public:
    long long maximumSubarraySum(vector<int>& nums, int k) {
        long long res = LLONG_MIN, sum = 0;
        unordered_map<int, long long> minS;

        for (int x : nums) {
            auto it = minS.find(x + k);
            if (it != minS.end()) {
                res = max(res, sum + x - it->second);
            }

            it = minS.find(x - k);
            if (it != minS.end()) {
                res = max(res, sum + x - it->second);
            }

            it = minS.find(x);
            if (it == minS.end() || sum < it->second) {
                minS[x] = sum;
            }
            sum += x;
        }
        return res == LLONG_MIN ? 0 : res;
    }
};