๋ฐ์ํ
[BOJ] 1806๋ฒ ๋ถ๋ถํฉ
https://www.acmicpc.net/problem/1806
๋ฌธ์ ์ ๊ทผ
ํฌ ํฌ์ธํฐ๋ฅผ ์ด์ฉํด์ ๋ฌธ์ ๋ฅผ ํ์๋ค.
deque์ ์ด๋ถ ํ์์ ์ด์ฉํด์๋ ํ ์ ์๋ค๊ณ ํ๋๋ฐ ๋ถ๋ฅ๊ฐ ํฌ ํฌ์ธํฐ๋ผ์ ํฌ ํฌ์ธํฐ๋ฅผ ์ฌ์ฉํด์ ํ์๋ค.
start์ end์ธ ๋ ๊ฐ์ ์ธ๋ฑ์ค๋ฅผ ์ฌ์ฉํ๊ณ sum์ด t(๋ชฉํ ๊ฐ)๋ณด๋ค ์๊ฑฐ๋ ๊ฐ์ผ๋ฉด end๋ฅผ +1ํด์ ํ๊ฐ๋ฅผ ๋ ๋ํ๋๋ก ํ๊ณ , sum์ด t(๋ชฉํ ๊ฐ)๋ณด๋ค ํฌ๋ฉด start๋ฅผ +1 ํด์ ํฉ์์ ํ๊ฐ๋ฅผ ๋นผ์ ๋ชฉํ ๊ฐ์ ์ ๊ทผํ๋๋ก ํ๋ค.
ํฌ ํฌ์ธํฐ๋ฅผ ์ฌ์ฉํ๊ฒ ๋๋ฉด O(N)์ผ๋ก ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ์ ์๊ฒ ๋๋ ์ฅ์ ์ด ์๋ค.
Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class BOJ1806 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int t = Integer.parseInt(st.nextToken());
int[] arr = new int[n];
st = new StringTokenizer(br.readLine());
for(int i =0; i<n; i++){
arr[i] = Integer.parseInt(st.nextToken());
}
int start = 0;
int end = 0;
int sum = arr[0];
int answer = Integer.MAX_VALUE;
while(start<=end){
if(sum >= t){
answer = Math.min(answer, end - start + 1);
}
if(sum <= t){
end++;
if(end == n) break;
sum += arr[end];
} else {
sum -= arr[start];
start++;
if(start == n) break;
}
}
if(answer == Integer.MAX_VALUE) System.out.println(0);
else System.out.println(answer);
}
}
๋ฐ์ํ
'Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Algorithm/Java][๋ฐฑ์ค] 1197๋ฒ ์ต์ ์คํจ๋ ํธ๋ฆฌ (0) | 2022.05.22 |
---|---|
[Algorithm/Java][๋ฐฑ์ค] 1916๋ฒ ์ต์๋น์ฉ ๊ตฌํ๊ธฐ (0) | 2022.05.20 |
[Algorithm/Java][๋ฐฑ์ค] 1700๋ฒ ๋ฉํฐํญ ์ค์ผ์ค๋ง (0) | 2022.05.17 |
[Algorithm/Java][๋ฐฑ์ค] 1062๋ฒ ๊ฐ๋ฅด์นจ (0) | 2022.05.16 |
[Algorithm/Java][๋ฐฑ์ค] 2504๋ฒ ๊ดํธ์ ๊ฐ (0) | 2022.05.11 |