https://www.acmicpc.net/problem/1806
1806번: 부분합
첫째 줄에 N (10 ≤ N < 100,000)과 S (0 < S ≤ 100,000,000)가 주어진다. 둘째 줄에는 수열이 주어진다. 수열의 각 원소는 공백으로 구분되어져 있으며, 10,000이하의 자연수이다.
www.acmicpc.net
import java.util.*;
import java.io.*;
public class Main
{
static int N,S;
static int ans;
static void start(int[] x){
int start = 0;
int end = 0;
int sum = x[start];
while(true){
if(sum>=S){
ans = Math.min(end-start+1,ans);
sum -= x[start++];
}
else if(end==N-1) break;
else sum += x[++end];
}
}
public static void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int[] arr;
ans = Integer.MAX_VALUE;
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
S = Integer.parseInt(st.nextToken());
arr = new int[N];
st = new StringTokenizer(br.readLine());
for(int i=0;i<N;i++){
arr[i] = Integer.parseInt(st.nextToken());
}
start(arr);
if(ans==Integer.MAX_VALUE) ans = 0;
System.out.println(ans);
}
}
투포인터로 모든 경우를 탐색할 수 있다는 것을 이해하는데에 조금 오래 걸리긴 했지만, 이해를 완료하였다 !
공부를 할수록 이해하는 속도가 빨라지는 것이 뿌듯하고 재미있다.
'알고리즘' 카테고리의 다른 글
[백준] BOJ2608 - 로마 숫자 (JAVA) (0) | 2023.04.13 |
---|---|
[백준] BOJ2992 - 크면서 작은 수 (JAVA) (0) | 2023.04.12 |
[백준] BOJ2075 - N번째 큰 수 (JAVA) (0) | 2023.04.11 |
슬라이딩 윈도우 / 투 포인터 (JAVA) (1) | 2023.04.11 |
[SWEA] SWEA 2105 - 디저트 카페 (JAVA) (0) | 2023.04.07 |