๊ด€๋ฆฌ ๋ฉ”๋‰ด

Daehyunii's Dev-blog

์—ฐ์† ๋ถ€๋ถ„์ˆ˜์—ด1(ํšจ์œจ์„ฑ-ํˆฌ ํฌ์ธํ„ฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜) ๋ณธ๋ฌธ

๐Ÿ“š Language & CS knowledge/Algorithm (๊ธฐ์ดˆ๋ฌธ์ œํ’€์ด)

์—ฐ์† ๋ถ€๋ถ„์ˆ˜์—ด1(ํšจ์œจ์„ฑ-ํˆฌ ํฌ์ธํ„ฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜)

Daehyunii 2022. 9. 2. 17:48

๋ฌธ์ œ(์ถœ์ฒ˜ : ์ธํ”„๋Ÿฐ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œํ’€์ด ๊ฐ•์˜, ์ •๋ณด์˜ฌ๋ฆผํ”ผ์•„๋“œ)

 

N๊ฐœ์˜ ์ˆ˜๋กœ ์ด๋ฃจ์–ด์ง„ ์ˆ˜์—ด์ด ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค.์ด ์ˆ˜์—ด์—์„œ ์—ฐ์†๋ถ€๋ถ„์ˆ˜์—ด์˜ ํ•ฉ์ด ํŠน์ •์ˆซ์ž M์ด ๋˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋ช‡ ๋ฒˆ ์žˆ๋Š”์ง€ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•˜์„ธ์š”.๋งŒ์•ฝ N=8, M=6์ด๊ณ  ์ˆ˜์—ด์ด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค๋ฉด 12131112 ํ•ฉ์ด 6์ด ๋˜๋Š” ์—ฐ์†๋ถ€๋ถ„์ˆ˜์—ด์€ {2, 1, 3}, {1, 3, 1, 1}, {3, 1, 1, 1}๋กœ ์ด 3๊ฐ€์ง€์ž…๋‹ˆ๋‹ค.

โ–ฃ ์ž…๋ ฅ์„ค๋ช…
์ฒซ์งธ ์ค„์— N(1≤N≤100,000), M(1≤M≤100,000,000)์ด ์ฃผ์–ด์ง„๋‹ค. ์ˆ˜์—ด์˜ ์›์†Œ๊ฐ’์€ 1,000์„ ๋„˜์ง€ ์•Š๋Š” ์ž์—ฐ์ˆ˜์ด๋‹ค.

โ–ฃ ์ถœ๋ ฅ์„ค๋ช…
์ฒซ์งธ ์ค„์— ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.

 

โ–ฃ ์ž…๋ ฅ์˜ˆ์ œ 1

8 6

12131112

 

โ–ฃ ์ถœ๋ ฅ์˜ˆ์ œ 1

3

Tip 

 

๋ฌธ์ œํ’€์ด

//๊ฐ•์˜ ๋“ฃ๊ณ  ๋‚ด๊ฐ€ ๋‹ค์‹œ ์ž‘์„ฑํ•œ ๋‹ต
function solution(arr, num){
    let answer = 0;
    let sum = 0;
    let lp = 0;

    for(let rp = 0 ; rp < arr.length ; rp++){
        sum += arr[rp];
        if(sum === num) answer++;
        while(sum >= num){
            sum -= arr[lp++];
            if(sum === num) answer++;
        }
    }
    return answer;
}

let arr=[1, 2, 1, 3, 1, 1, 1, 2];
console.log(solution(arr, 6));