Skip to content
Rain Hu's Workspace
Go back

[LeetCode] 2461. Maximum Sum of Distinct Subarrays With Length K

Rain Hu

2461. Maximum Sum of Distinct Subarrays With Length K


一、題目

You are given an integer array nums and an integer k. Find the maximum subarray sum of all the subarrays of nums that meet the following conditions:

Example 1:

Example 2:

Example 3:

Constraints:


二、分析

三、解題

1. Sliding Window

long long maximumSubarraySum(vector<int>& nums, int k) {
    unordered_map<int,int> map;
    int valid = 0;
    long long res = 0;
    long long sum = 0;
    int left = 0, right = 0;
    while (right < nums.size()) {
        int x = nums[right++];                      // 右指針移動
        sum += x;                                   // 將值加入和
        map[x]++;                                   // 記錄右指針移動時數字的個數
        if (map[x] == 1) valid++;                   // 右指針移動時,數字個數為 1 時,有效數加 1
        if (right - left == k) {                    // 將 window 控制在大小為 k
            if (valid == k) res = max(res, sum);    // 滿足條件,比較大小
            int y = nums[left++];                   // 左指針移動
            if (map[y] == 1) valid--;               // 左指針移動時,數字個數為 1 時,有效數減 1
            map[y]--;                               // 記錄左指針移動時數字的個數
            sum -= y;                               // 將值移去和
        }
    }
    return res;
}

回目錄 Catalog


Share this post on:

Previous
[LeetCode] 2462. Total Cost to Hire K
Next
[LeetCode] 2460. Apply Operations to an Array