文章目录
题目描述
题解思路
我们遍历长度为k的窗口,用一个哈希表记录窗口内的所有元素(用来对窗口内元素去重),我们取哈希表中元素数量等于k的窗口总和的最大值
题解代码
rust
use std::collections::{HashMap};
impl Solution {
pub fn maximum_subarray_sum(nums: Vec<i32>, k: i32) -> i64 {
let mut win = HashMap::new();
let mut sum = 0;
for i in 0..k as usize {
win.insert(nums[i], i);
sum += nums[i] as i64;
}
let mut ans = 0i64;
if win.len() >= k as usize {
ans = ans.max(sum);
}
for i in k as usize..nums.len() {
if let Some(&start) = win.get(&nums[i-k as usize]) {
if start == i - k as usize {
win.remove(&nums[i-k as usize]);
}
}
win.insert(nums[i], i);
sum += (nums[i] - nums[i-k as usize]) as i64;
if win.len() == k as usize {
ans = ans.max(sum);
}
}
ans
}
}
题目链接
https://leetcode.cn/problems/maximum-sum-of-distinct-subarrays-with-length-k/description/