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

Daehyunii's Dev-blog

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

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

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

Daehyunii 2022. 9. 2. 17:48

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

 

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

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

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

 

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

5 5

1 3 1 2 3

 

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

10

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];
        while(sum > num){
            sum -= arr[lp++];
        }
        answer += (rp - lp + 1);
    }
    return answer;
}

let a=[1, 3, 1, 2, 3];
console.log(solution(a, 5));