【美团笔试题】连续最大子序列整除k

【思路】

滑动窗口“掐头去尾”

【正确代码】

 1 import java.util.Scanner;
 2 
 3 public class Main {
 4     public static void main(String[] args) {
 5         Scanner sc = new Scanner(System.in);
 6         while (sc.hasNext()) {
 7             int n = sc.nextInt();
 8             int[] arr = new int[n];
 9             for (int i = 0; i < n; i++) {
10                 arr[i] = sc.nextInt();
11             }
12             int k = sc.nextInt();
13             for (int i = n; i > 0; i--) {//记录元素个数
14                 int sum = 0;
15                 for (int j = 0; j < i; j++) {
16                     sum += arr[j];
17 
18                 }
19                 if (sum % k == 0) {
20                     System.out.println(i);
21                     return;
22                 }
23                 for (int j = 1; j < n - i; j++) {//滑动只需要n-i次循环
24                     sum = sum + arr[j - 1 + i] - arr[j - 1];
25                     if (sum % k == 0) {
26                         System.out.println(i);
27                         return;
28                     }
29                 }
30             }
31             System.out.println(0);
32             return;
33         }
34     }
35 }

 

posted @ 2017-08-31 22:54  菜鸟更要虚心学习  阅读(487)  评论(0编辑  收藏  举报