https://www.acmicpc.net/problem/1806
10,000 이하의 자연수로 이루어진 길이 N짜리 수열이 주어진다. 이 수열에서 연속된 수들의 부분합 중에 그 합이 S 이상이 되는 것 중, 가장 짧은 것의 길이를 구하는 프로그램을 작성하시오.
첫째 줄에 N (10 ≤ N < 100,000)과 S (0 < S ≤ 100,000,000)가 주어진다. 둘째 줄에는 수열이 주어진다. 수열의 각 원소는 공백으로 구분되어져 있으며, 10,000이하의 자연수이다.
투포인터를 이용해 풀 수 있다.
링크의 풀이법과 다른점
- 합이 S이상이기 때문에, 조건을 크거나 같을 때로 잡아야 함
- 개수가 아니라 start와 end 사이 길이를 구해야 함
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class partSum_1806 {
static int[] arr;
public static void solution() throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(bf.readLine());
int n = Integer.parseInt(st.nextToken());
int s = Integer.parseInt(st.nextToken());
int length = Integer.MAX_VALUE;
arr = new int[n];
st = new StringTokenizer(bf.readLine());
for(int i=0;i<n;i++){
arr[i] = Integer.parseInt(st.nextToken());
}
int end = 0;
int sum = 0;
for(int i=0;i<n;i++){
while(sum<s && end<n){
sum += arr[end];
end++;
}
if(sum>=s && length > end-i){
length = end-i;
}
sum -= arr[i];
}
if(length == Integer.MAX_VALUE){
System.out.println(0);
return;
}
System.out.println(length);
}
}