给定一个数组arr,该数组无序,但每个值均为正数,再给定一个正数k。求arr的所有子数组中所有元素相加和为k的最长子数组的长度
例如,arr = [1, 2, 1, 1, 1], k = 3
累加和为3的最长子数组为[1, 1, 1],所以结果返回3
import java.util.Scanner;
public class Main {
private static int solve(int[] arr, int aim) {
if (arr == null || arr.length == 0) {
return 0;
}
int ret = 0;
int sum = arr[0];
int l = 0, r = 0;
while (l <= r) {
if (sum == aim) {
ret = Math.max(ret, r - l + 1);
sum -= arr[l++];
} else if (sum > aim) {
sum -= arr[l++];
} else {
r++;
if (r == arr.length) {
break;
}
sum += arr[r];
}
}
return ret;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int n = in.nextInt();
int aim = in.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; ++i) {
arr[i] = in.nextInt();
}
System.out.println(solve(arr, aim));
}
}
}
心之所向,素履以往 生如逆旅,一苇以航