๐ฉ๐ปโ๐ป๋ฌธ์ ๋งํฌ
[์ธํ๋ฐ ์น์
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;
}