跳转至

和等于 k 的最长子数组长度⚓︎

Leetcode题目链接

描述⚓︎

详见中文题目链接

解答⚓︎

class Solution {
public:
    int maxSubArrayLen(vector<int>& nums, int k) {
        unordered_map<long long, int> prefixMap;
        prefixMap[0] = -1;

        int res = 0;
        long long sum = 0;
        for (int i = 0; i < nums.size(); i++) {
            sum += nums[i];

            if (prefixMap.find(sum - k) != prefixMap.end()) {
                res = max(res, i - prefixMap[sum - k]);
            }
            if (prefixMap.find(sum) == prefixMap.end()) {
                prefixMap[sum] = i;
            }
        }

        return res;
    }
};