每日一道编程题(11):清华912

每日一道编程题(11):清华912

题目描述:
求一个数组A中连续相同数字的和等于s的最长子数组长度. 例如A={1,1,2,1,1,1,2,1}, s=3.则所求子数组长度为 3 , 要求算法时间复杂度不超过 O(n),空间复杂度不超过 O(1) 。

import java.util.Scanner;

public class Tinghua912 {
    public static void main(String[] args) {
        //求数组的最大子序列和
        Scanner in = new Scanner(System.in);
        //输入s
        int s = in.nextInt();

        //输入数组的数据
        int N = in.nextInt();
        int[] a = new int[N];

        for (int i = 0; i < N; i++) {
            a[i] = in.nextInt();
        }
        //用来求最大数组的子列和
        System.out.println(MAXnSum(a, s));
    }

    private static int MAXnSum(int[] a, int s1) {
        int max = 0; //代表当前最大长度
        int sum = a[0];//代表最大的和
        int last = a[0]; //代表前一个数字
        int count = 1;    //记录当前长度
        if (s1 == sum) {   //排除极端情况
            max = 1;
            count = 0;
        }

        //通过for遍历
        for (int i = 1; i < a.length; i++) {
            sum += a[i];
            count++;
            if (a[i] != last || sum > s1) {
                sum = a[i];
                count = 1;

            } else if (s1 == sum) {
                if (count > max) {
                    max = count;
                }
                sum = 0;    //进行下一次子列和的计算
                count = 0;
            }
            last = a[i];
        }
        return max;

    }
}

猜你喜欢

转载自blog.csdn.net/qq_41033299/article/details/88903770