์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜5] ์—ฐ์† ๋ถ€๋ถ„์ˆ˜์—ด 1 (Javascript)

์€์ง„ 2021. 6. 25. 13:22

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜5] ์—ฐ์† ๋ถ€๋ถ„์ˆ˜์—ด 1 (Javascript)
์œ ๋ฃŒ ๊ฐ•์˜์ธ ๊ด€๊ณ„๋กœ ๋ฌธ์ œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.

 

โœ๏ธIdea Sketch

2021-06-25

1. left์™€ right ์ธ๋ฑ์Šค๋ฅผ ๋งŒ๋“ ๋‹ค

2. left๋ถ€ํ„ฐ right๊นŒ์ง€์˜ ํ•ฉ์ด m๋ณด๋‹ค ํฌ๋ฉด left++

3. left๋ถ€ํ„ฐ right๊นŒ์ง€์˜ ํ•ฉ์ด m๋ณด๋‹ค ์ž‘์œผ๋ฉด right++

4. m๊ณผ ๊ฐ™์œผ๋ฉด cnt++

5. ์ „์œ„/ํ›„์œ„์—ฐ์‚ฐ์ž ์ฃผ์˜

 

โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-06-25

function solution(arr, m) {
  let left = 0, right = 0;
  let cnt = 0;
  let sum = arr[0];

  while (left < arr.length && right < arr.length) {
    if (sum === m) cnt++;
    if (sum <= m) sum += arr[++right];
    else if (sum > m) sum -= arr[left++];
  }
  return cnt;
}