ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

Algorithm/Baekjoon

[JavaScript] ๋ฐฑ์ค€ 1806๋ฒˆ - ๋ถ€๋ถ„ํ•ฉ

๊ฐœ๋ฐœ๊ฐœ๊ตด๐Ÿธ 2022. 8. 1. 16:47

[๋ฌธ์ œ]

https://www.acmicpc.net/problem/1806

 

1806๋ฒˆ: ๋ถ€๋ถ„ํ•ฉ

์ฒซ์งธ ์ค„์— N (10 ≤ N < 100,000)๊ณผ S (0 < S ≤ 100,000,000)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” ์ˆ˜์—ด์ด ์ฃผ์–ด์ง„๋‹ค. ์ˆ˜์—ด์˜ ๊ฐ ์›์†Œ๋Š” ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„๋˜์–ด์ ธ ์žˆ์œผ๋ฉฐ, 10,000์ดํ•˜์˜ ์ž์—ฐ์ˆ˜์ด๋‹ค.

www.acmicpc.net

[ํ’€์ด]

์ˆ˜์—ด์˜ ๋ถ€๋ถ„ํ•ฉ์„ ๊ตฌํ•˜๋Š” ๋ฌธ์ œ๋กœ ํˆฌํฌ์ธํ„ฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ™œ์šฉํ•˜์—ฌ ํ’€์ดํ•˜์˜€์Šต๋‹ˆ๋‹ค.

 

์˜ˆ์‹œ 1๊ณผ ๊ฐ™์ด ๊ธธ์ด๊ฐ€ N(10)์ธ ์ˆ˜์—ด [ 5, 1, 3, 5, 10, 7, 4, 9, 2,  8 ]์ด ์žˆ์„ ๋•Œ,

 

์•„๋ž˜์™€ ๊ฐ™์ด start = 0 , end = 0, sum = 5 ๋กœ ํˆฌํฌ์ธํ„ฐ ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค.

 

<- start <- end 3 5 10 7 4 9 2 8

 

๋งŒ์•ฝ sum์ด S(15)๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๋‹ค๋ฉด end++์„ ํ•ด์ฃผ์–ด sum์— ์ˆ˜์—ด[end]๊ฐ’์„ ๋”ํ•ด sum ํฌ๊ธฐ๋ฅผ ํ‚ค์›Œ์ค๋‹ˆ๋‹ค.

๋งŒ์•ฝ sum์ด S(15)๋ณด๋‹ค ํฌ๋‹ค๋ฉด, ์ˆ˜์—ด[start]๊ฐ’์„ sum์—์„œ ๋นผ์ฃผ์–ด sum์„ ์ž‘๊ฒŒ ๋งŒ๋“ค๊ณ  start++๋ฅผ ํ•ฉ๋‹ˆ๋‹ค.

 

๋”ฐ๋ผ์„œ 5 <= 15 ์ด๋ฏ€๋กœ end + 1์ธ ์ˆ˜์—ด[1]์˜ 1์„ ๋ฐ”๋ผ๋ณด๊ฒŒ ๋˜๊ณ  sum์€ 6์ด ๋ฉ๋‹ˆ๋‹ค.

 

์ด๋Ÿฐ์‹์œผ๋กœ start์™€ end๊ฐ’์ด N ๋ณด๋‹ค ์ž‘์„ ๋•Œ๊นŒ์ง€(์ˆ˜์—ด์˜ ๋งˆ์ง€๋ง‰๊นŒ์ง€) ๊ฐฑ์‹ ํ•˜๋ฉฐ ๋งŒ์•ฝ sum์ด S๋ณด๋‹ค ํฐ ๊ฒฝ์šฐ end - start + 1์„ ํ†ตํ•ด ๋ช‡๊ฐœ์˜ ์ˆซ์ž๊ฐ€ ์—ฐ์†๋˜์–ด ์žˆ๋Š”์ง€ ๊ตฌํ•ด min์„ ๊ฐฑ์‹ ํ•˜์—ฌ ์ค๋‹ˆ๋‹ค.

 

ํƒ์ƒ‰ ๊ณผ์ •์€ ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

 

start: 0 end: 0 sum: 5
start: 0 end: 1 sum: 6
start: 0 end: 2 sum: 9
start: 0 end: 3 sum: 14
start: 0 end: 4 sum: 24 => 15๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ธฐ ๋•Œ๋ฌธ์— 4 - 0 + 1 = 5 => min = 5๋กœ ๊ฐฑ์‹ 
start: 1 end: 4 sum: 19 => min = 4๋กœ ๊ฐฑ์‹ 
start: 2 end: 4 sum: 18 => min = 3๋กœ ๊ฐฑ์‹ 
start: 3 end: 4 sum: 15 => min = 2๋กœ ๊ฐฑ์‹ 
start: 3 end: 5 sum: 22 => 3์€ ๊ธฐ์กด min 2๋ณด๋‹ค ํฌ๊ธฐ ๋•Œ๋ฌธ์— ๊ฐฑ์‹  X
start: 4 end: 5 sum: 17 => 2๋Š” ๊ธฐ์กด min๊ณผ ๊ฐ™์•„์„œ ๊ฐฑ์‹  X
start: 5 end: 5 sum: 7
start: 5 end: 6 sum: 11
start: 5 end: 7 sum: 20 => 3์€ ๊ธฐ์กด min๋ณด๋‹ค ์ปค์„œ ๊ฐฑ์‹  X
start: 6 end: 7 sum: 13
start: 6 end: 8 sum: 15 => 3 ๊ฐฑ์‹  X
start: 6 end: 9 sum: 23 => 4 ๊ฐฑ์‹  X
start: 7 end: 9 sum: 19 => 3 ๊ฐฑ์‹  X
start: 8 end: 9 sum: 10

 

๋”ฐ๋ผ์„œ ์—ฐ์†๋œ ์ตœ์†Œ ๊ฐœ์ˆ˜์ธ min ์€ 2๊ฐ€ ๋ฉ๋‹ˆ๋‹ค.

[์ฝ”๋“œ]

const fs = require("fs");
let input = fs.readFileSync("/dev/stdin").toString().split('\n');

const [N, S] = input[0].split(" ").map(Number);
const numArr = input[1].split(" ").map(Number);

let start = 0;
let end = 0;
let min = Number.MAX_VALUE;

let sum = numArr[0];
while(start < N && end < N) {
    if(sum >= S) {
        if(min > end - start + 1) {
            min = end - start + 1;
        }
    }
    
    if(sum <= S) {
        end++;
        sum += numArr[end];
    } else {
        sum -= numArr[start];
        start++;
    }
}

min === Number.MAX_VALUE ? console.log(0) : console.log(min);