输入: 5 3 1 2 1 1 1 输出: 3
import java.util.Scanner; public class Main{ public static void main(String[] args){ Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int k = scanner.nextInt(); int[] arr = new int[n]; for(int i=0;i<n;i++){ arr[i] = scanner.nextInt(); } int start=0,end=0,sum=arr[start],maxLen=Integer.MIN_VALUE; while(end<n){ if(sum==k){ maxLen = Math.max(end - start + 1,maxLen); sum -= arr[start++]; } else if(sum >k){ sum -= arr[start++]; } else { end++; if(end == n){ break; } sum += arr[end]; } } System.out.println(maxLen); } }