A sequence of N positive integers (10 < N < 100 000), each of them less than or equal 10000, and a positive integer S (S < 100 000 000) are given. Write a program to find the minimal length of the subsequence of consecutive elements of the sequence, the sum of which is greater than or equal to S.
Input
The first line is the number of test cases. For each test case the program has to read the numbers N and S, separated by an interval, from the first line. The numbers of the sequence are given in the second line of the test case, separated by intervals. The input will finish with the end of file.
Output
For each the case the program has to print the result on separate line of the output file.if no answer, print 0.
Sample Input
2 10 15 5 1 3 5 10 7 4 9 2 8 5 11 1 2 3 4 5
Sample Output
2
3
对于这道题来说,用队列理解尺取感觉最合适不过了。
分析一下这个数据
代码思路按照如下分析写得。
5 1 3 5 10 7 4 9 2 8
5 1 3 5 10 7 4 9 2 8
5 1 3 5 10 7 4 9 2 8
5 1 3 5 10 7 4 9 2 8 ===》ans=2最终答案,最少序列
5 1 3 5 10 7 4 9 2 8
5 1 3 5 10 7 4 9 2 8
5 1 3 5 10 7 4 9 2 8
5 1 3 5 10 7 4 9 2 8
其实就是满足不满足条件出队。。。
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
public class MainF {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num = in.nextInt();
int n,m;
while(num--!=0) {
n = in.nextInt();
m = in.nextInt();
Queue<Integer> queue = new LinkedList<Integer>();
List<Integer> list = new ArrayList<Integer>();
for(int i=0;i<n;i++) {
list.add(in.nextInt());
}
Integer sum = 0;
int ans = 999999999;
for(int i=0;i<n ;i++) {
//如果值小就一直加
while(i<n && sum + list.get(i)< m ) {
queue.offer(list.get(i));
sum+=list.get(i);
i++;
}
if(i>=n)break;
queue.offer(list.get(i));
sum += list.get(i);
//超过了给定值,就开始记录
while(i<n && sum >= m ) {
//先记录长度
if(ans > queue.size()) {
ans = queue.size();
}
if(!queue.isEmpty()) {
//出队,少一个元素看看总的值sum是否还大于给定值m
Integer fileNum = queue.poll();
sum-=fileNum;
}else {
break;
}
}
}
if (ans>n) ans = 0;
System.out.println(ans);
}
}
}