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

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

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

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

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


โœ๏ธIdea Sketch

2021-06-25

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

1) cnt += (left๋ถ€ํ„ฐ right๊นŒ์ง€ ์›์†Œ์˜ ๊ฐœ์ˆ˜)

cnt += right - left + 1

2) right++

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

3. Example

1) left๊ฐ€ 0, right๊ฐ€ 2์ผ ๋•Œ --> ์›์†Œ๋Š” 1, 3, 1 --> sum === m (5 === 5)

  • ์—ฐ์†๋ถ€๋ถ„์ˆ˜์—ด {1, 3, 1}, {3, 1}, {1} ์ด 3๊ฐœ๊ฐ€ ์ถ”๊ฐ€๋จ

2) left๊ฐ€ 0, right๊ฐ€ 3์ผ ๋•Œ --> ์›์†Œ๋Š” 1, 3, 1, 2 ==> sum > m (7 > 5)
3) left๊ฐ€ 1, right๊ฐ€ 3์ผ ๋•Œ --> ์›์†Œ๋Š” 3, 1, 2 ==> sum > m (6 > 5)
4) left๊ฐ€ 2, right๊ฐ€ 3์ผ ๋•Œ --> ์›์†Œ๋Š” 1, 2 ==> sum < m (3 < 5)

  • ์—ฐ์†๋ถ€๋ถ„์ˆ˜์—ด {1, 2}, {2} ์ด 2๊ฐœ๊ฐ€ ์ถ”๊ฐ€๋จ


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

2021-06-25

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

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

  return cnt;
}