08 未排序正数数组中累加和为给定值的最长子数组的长度
Table of Contents

ac

双指针法最优解

import java.util.Scanner;

public class Main {

    public static Scanner sc = new Scanner(System.in);

    /*
5 3
1 2 1 1 1

5 4
1 2 1 1 1

5 6
1 2 1 1 1

5 7
1 2 1 1 1
     */
    public static void main(String[] args) {

        int n = sc.nextInt();
        int k = sc.nextInt();
        int[] arr = new int[n];
        for(int i=0;i<n;i++){
            arr[i] = sc.nextInt();
        }
        // 双指针维持一个区间,[left, right] 和 sum, 不断的移动
        int left = 0;
        int right = 0;
        int sum = arr[left];
        int len = 0;
        while(right < n){
            if(sum == k){
                len = Math.max(len, right - left + 1);
                sum -= arr[left];
                left++;
            }else if(sum > k){
                sum -= arr[left];
                left++;
            }else {
                right++;
                if(right == n){
                    break;
                }
                sum += arr[right];
            }
        }
        System.out.println(len);
    }

}