Description
牛客网 2018校招真题 K的倍数
Solving Ideas
sum[i + 1]
: 表示序列p[0]...p[i]
的和
从长度最大的子串开始判断,当剩余需要判断子串长度不可能大于已得最优解时,终止循环。
Solution
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author wylu
*/
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int[] p = new int[n];
String[] strs = br.readLine().split(" ");
for (int i = 0; i < n; i++) {
p[i] = Integer.parseInt(strs[i]);
}
int k = Integer.parseInt(br.readLine());
//sum[i + 1]: 序列p[0]...p[i]的和
long[] sum = new long[n + 1];
for (int i = 0; i < n; i++) sum[i + 1] = sum[i] + p[i];
int res = 0;
for (int i = n; i >= 1; i--) {
for (int j = 0; j < i; j++) {
if ((sum[i] - sum[j]) % k == 0) {
res = Math.max(res, i - j);
break;
}
}
if (res >= i - 1) break;
}
System.out.println(res);
}
}