diff --git a/src/main/java/com/cool/ling_cha_mount/sliding_windows/Num2461.java b/src/main/java/com/cool/ling_cha_mount/sliding_windows/Num2461.java new file mode 100644 index 0000000..83e9c3a --- /dev/null +++ b/src/main/java/com/cool/ling_cha_mount/sliding_windows/Num2461.java @@ -0,0 +1,55 @@ +package com.cool.ling_cha_mount.sliding_windows; + +import java.util.HashMap; +import java.util.Map; + +/** + * Created with IntelliJ IDEA. + * + * @Author: Cool + * @Date: 2024/10/10/17:11 + * @Description: 2461. 长度为 K 子数组中的最大和 + * Hard 2 + * Level 4 + * Score 1553 + */ +public class Num2461 { + + + /** + * 1 + * + * @Author Cool + * @Date 17:11 2024/10/10 + **/ + public long maximumSubarraySum(int[] nums, int k) { + Map map = new HashMap<>(); + long sum = 0; + for (int i = 0; i < k; i++) { + map.put(nums[i], map.getOrDefault(nums[i], 0) + 1); + sum += nums[i]; + } + long res = 0; + if (map.size() == k) { + res = sum; + } + for (int i = k; i < nums.length; i++) { + Integer left = map.get(nums[i - k]); + if (left==1) { + map.remove(nums[i - k]); + } else { + map.put(nums[i - k], left - 1); + } + map.put(nums[i], map.getOrDefault(nums[i], 0) + 1); + sum -= nums[i - k]; + sum += nums[i]; + if (map.size() == k) { + res = Math.max(sum, res); + } + } + return res; + } + + + +}