1 import java.util.*; 2 3 public class Main { // 注意类名必须为Main 4 public static void main(String[] args) { 5 Scanner scan = new Scanner(System.in); 6 int number = Integer.parseInt(scan.nextLine()); 7 // number个测试样例 8 for (int k = 0; k < number; k++){ 9 // 输入数据 10 String str = scan.nextLine(); 11 int w = Integer.parseInt(scan.nextLine()); 12 String[] strs = str.split(" "); 13 int n = strs.length; 14 if (w > n) w = n; 15 int[] arr = new int[n]; 16 for (int i = 0; i < n; i++) 17 arr[i] = Integer.parseInt(strs[i]); 18 // 双端队列,这里只存储元素的下标 19 LinkedList<Integer> list = new LinkedList<>(); 20 // 初始化 21 list.addLast(0); 22 23 for (int i = 1; i < w; i++) { 24 while (list.size() > 0 && arr[list.getLast()] < arr[i]) 25 list.pollLast(); 26 list.addLast(i); 27 } 28 int sum = arr[list.getFirst()]; 29 // 窗口移动,增加元素arr[i],除去元素arr[i-w] 30 for (int i = w; i < n; i++) { 31 // 增加元素arr[i] 32 while (list.size() > 0 && arr[list.peekLast()] < arr[i]) 33 list.pollLast(); 34 list.addLast(i); 35 // 除去元素arr[i-w] 36 if (list.getFirst() == i-w) 37 list.pollFirst(); 38 sum += arr[list.getFirst()]; 39 } 40 System.out.println(sum); 41 } 42 scan.close(); 43 } 44 45 }