본문 바로가기

알고리즘/백준

[백준] 1806 부분합

문제링크 : www.acmicpc.net/problem/1806

 

1806번: 부분합

첫째 줄에 N (10 ≤ N < 100,000)과 S (0 < S ≤ 100,000,000)가 주어진다. 둘째 줄에는 수열이 주어진다. 수열의 각 원소는 공백으로 구분되어져 있으며, 10,000이하의 자연수이다.

www.acmicpc.net

 

기본적인 투포인터 문제다.

개인적으로 이런 문제가 왜 골드3인지는 모르겠다.

가끔 자바로도 문제를 풀 것 같다.

 

 

내코드

import java.io.*;
import java.util.*;

public class Main {
	public static int[] arr;
	public static void main(String[] args)throws Exception {
		int N,S;
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st = new StringTokenizer(br.readLine());
		
		N = Integer.parseInt(st.nextToken());
		S = Integer.parseInt(st.nextToken());
		arr = new int[N+1];
		st = new StringTokenizer(br.readLine());
		
		for(int i=0;i<N;i++) {
			arr[i] = Integer.parseInt(st.nextToken());
		}
		int left = 0;
		int right = 0;
		int temp_sum = arr[0];
		int min_len = Integer.MAX_VALUE;
		while(right<N) {
			if(temp_sum >= S) {
				min_len = Math.min(min_len, right-left+1);
				temp_sum-= arr[left];
				left++; continue;
			}else {
				right++;
				temp_sum +=arr[right];
			}
		}
		if(min_len == Integer.MAX_VALUE) {
			System.out.println(0);
		}else {
			System.out.println(min_len);
		}
	}

}

'알고리즘 > 백준' 카테고리의 다른 글

[백준] 2042 구간 합 구하기  (2) 2020.12.02
[백준] 1072 게임  (0) 2020.12.01
[백준] 1920 수 찾기  (0) 2020.11.24
[백준] 2470 두 용액  (0) 2020.11.19
[백준] 18228 펭귄추락  (0) 2020.11.11