题解 | #未排序正数数组中累加和为给定值的最长子数组的长度#
未排序正数数组中累加和为给定值的最长子数组的长度
http://www.nowcoder.com/practice/a4e34287fa1b41f9bd41f957efbd5dff
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
int left = 0;
int right = 0;
int sum = arr[left];
int len = 0;
while (right < n) {
if (sum == k) {
len = Math.max(right - left + 1, len);
sum -= arr[left++];
} else if (sum > k) {
sum -= arr[left++];
} else {
right++;
if (right == n) {
break;
}
sum += arr[right];
}
}
System.out.println(len);
}
}