平均数为k的最长连续子数组
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), k = sc.nextInt();
long pre = 0, cur;
// 存的是<前缀和,下标>
Map<Long, Integer> map = new HashMap<>();
map.put(0L, 0);
int ans = -1;
for (int i = 1; i <= n; i++) {
cur = pre + sc.nextInt() - k;
if (map.containsKey(cur-0)) {
ans = Math.max(ans, i - map.get(cur));
}
else map.put(cur, i);
pre = cur;
}
System.out.println(ans);
}
}
public class Solution {
public int subarraySum(int[] nums, int k) {
// 和为k的连续子数组的个数, 当前前缀和
int count = 0, pre = 0;
// map存储<前缀和 , i位置上符合条件的次数>
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
// 循环
for(int i = 0; i< nums.length; i++) {
pre += nums[i];
// 以i结尾的和为k的
if(map.containsKey(pre - k)) {
count += map.get(pre - k);
}
map.put(pre, map.getOrDefault(pre, 0) + 1);
}
return count;
}
}