2024/10/09 灵茶题单 滑动窗口

This commit is contained in:
Cool 2024-10-09 17:33:39 +08:00
parent 52bc75308c
commit 37e77fea51
1 changed files with 52 additions and 0 deletions

View File

@ -0,0 +1,52 @@
package com.cool.ling_cha_mount.sliding_windows;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
*
* @Author: Cool
* @Date: 2024/10/09/17:24
* @Description:
*/
public class Num2841 {
public long maxSum(List<Integer> nums, int m, int k) {
Map<Integer,Integer> map=new HashMap<>();
long sum=0;
for(int i=0;i<k;i++){
Integer integer =nums.get(i);
if(!map.containsKey(integer)){
map.put(integer,1);
}else{
map.put(integer,map.get(integer)+1);
}
sum+= integer;
}
long res=0;
if(map.size()>=m){
res=sum;
}
for(int i=k;i<nums.size();i++){
Integer left=nums.get(i-k);
Integer right=nums.get(i);
map.put(left,map.get(left)-1);
if(map.get(left).equals(0)){
map.remove(left);
}
if(!map.containsKey(right)){
map.put(right,1);
}else{
map.put(right,map.get(right)+1);
}
sum-=left;
sum+=right;
if(map.size()>=m){
res=Math.max(res,sum);
}
}
return res;
}
}