滑动窗口:因为只要最大得分,只要保存窗口内的得分即可。根据当前i与i+m的sleep状态,更新滑动窗口内的得分,一次遍历即可。
import java.util.Scanner; public class Main { public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int[] ints = new int[n];//score for(int i = 0; i < n; i++){ ints[i] = sc.nextInt(); } int[] sleep = new int[n];//is sleep for(int i = 0; i < n; i++){ sleep[i] = sc.nextInt(); } int temp = 0; //滑动窗口 for(int i = 0; i < m; i++){ if(sleep[i] == 0){ temp += ints[i]; } } int max = temp; int sum = 0; for(int i = 0; i < n; i++){ if(sleep[i] == 0){ temp -= ints[i]; }else{ sum += ints[i]; } if(i + m < n && sleep[i + m] == 0){ temp += ints[i + m]; } max = Math.max(max, temp); } System.out.println(sum + max); } }