[LeetCode] 2841. Maximum Sum of Almost Unique Subarray

CNoodle發表於2024-11-10

You are given an integer array nums and two positive integers m and k.

Return the maximum sum out of all almost unique subarrays of length k of nums. If no such subarray exists, return 0.

A subarray of nums is almost unique if it contains at least m distinct elements.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:
Input: nums = [2,6,7,3,1,7], m = 3, k = 4
Output: 18
Explanation: There are 3 almost unique subarrays of size k = 4. These subarrays are [2, 6, 7, 3], [6, 7, 3, 1], and [7, 3, 1, 7]. Among these subarrays, the one with the maximum sum is [2, 6, 7, 3] which has a sum of 18.

Example 2:
Input: nums = [5,9,9,2,4,5,4], m = 1, k = 3
Output: 23
Explanation: There are 5 almost unique subarrays of size k. These subarrays are [5, 9, 9], [9, 9, 2], [9, 2, 4], [2, 4, 5], and [4, 5, 4]. Among these subarrays, the one with the maximum sum is [5, 9, 9] which has a sum of 23.

Example 3:
Input: nums = [1,2,1,2,1,2,1], m = 3, k = 3
Output: 0
Explanation: There are no subarrays of size k = 3 that contain at least m = 3 distinct elements in the given array [1,2,1,2,1,2,1]. Therefore, no almost unique subarrays exist, and the maximum sum is 0.

Constraints:
1 <= nums.length <= 2 * 104
1 <= m <= k <= nums.length
1 <= nums[i] <= 109

幾乎唯一子陣列的最大和。

給你一個整數陣列 nums 和兩個正整數 m 和 k 。

請你返回 nums 中長度為 k 的 幾乎唯一 子陣列的 最大和 ,如果不存在幾乎唯一子陣列,請你返回 0 。

如果 nums 的一個子陣列有至少 m 個互不相同的元素,我們稱它是 幾乎唯一 子陣列。

子陣列指的是一個陣列中一段連續 非空 的元素序列。

思路

題目要求我們找的是一個長度為 k 的子陣列。這道題的思路就是偏找一個固定長度的滑動視窗,然後視窗內元素滿足一定條件。具體到這個題,我們找的就是一個長度為 k 的子陣列,在這個長度為 k 的視窗內,不同元素個數需要至少為 m 個。

那麼我們可以用一個 hashmap 來統計視窗內的元素情況,如果 map.size() >= m,則視窗內的元素才滿足條件,才能把視窗內元素的計算和。

複雜度

時間O(n)
空間O(n)

程式碼

Java實現

class Solution {
    public long maxSum(List<Integer> nums, int m, int k) {
        long sum = 0;
        long res = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < k; i++) {
            int num = nums.get(i);
            map.put(num, map.getOrDefault(num, 0) + 1);
            sum += nums.get(i);
        }
        if (map.size() >= m) {
            res = sum;
        }

        for (int i = k; i < nums.size(); i++) {
            int cur = nums.get(i);
            int pre = nums.get(i - k);
            map.put(cur, map.getOrDefault(cur, 0) + 1);
            int c = map.getOrDefault(pre, 0);
            if (c > 1) {
                map.put(pre, c - 1);
            } else {
                map.remove(pre);
            }
            sum += cur;
            sum -= pre;
            if (map.size() >= m) {
                res = Math.max(res, sum);
            }
        }
        return res;
    }
}

相關文章