๐ฉ๐ปโ๐ป๋ฌธ์ ๋งํฌ
[๋ฐฑ์ค 2003] ์๋ค์ ํฉ 2 (Javascript)
โ๏ธIdea Sketch
2021-07-19
1. ๋ฌธ์ ์ดํด
- ์ฐ์ํ ์๋ค์ ํฉ์ด M์ ๋๋ ๊ฒฝ์ฐ์ ์ ๊ตฌํ๊ธฐ
2. ๋ฐฑ์ค javascript ์ ๋ ฅ๋ฐ๊ธฐ
const fs = require('fs');
const stdin = (process.platform === 'linux'
? fs.readFileSync('/dev/stdin').toString()
: `10 5
1 2 3 4 2 5 3 1 1 2`
).split('\n');
let [N, M] = stdin[0].split(' ').map(Number);
let input = stdin[1].split(' ').map(Number);
3. ๋ก์ง
- left, right ์ฌ๋ผ์ด๋ฉ ์๋์ฐ
- sum์ด M๋ณด๋ค ์์ผ๋ฉด sum += input[++right];
- sum์ด M๋ณด๋ค ํฌ๋ฉด sum -= input[left++];
- sum์ด M๊ณผ ๊ฐ์ผ๋ฉด cnt++, sum += input[++right];
- ์ธ์ ๊น์ง ๋ฐ๋ณตํ๋์ : left < arr.length && right < arr.length
- left right sum ์ด๊ธฐ๊ฐ : 0, 1, input[left] + input[right]
โ๏ธ์์ค์ฝ๋
2021-07-19 ์คํจ
๋ฐ๋ก
4 2 // N, M
2 3 1 1
๋ฌธ์ ์ํฉ : ์ฒซ๋ฒ์งธ ์์ 2๊ฐ M๊ณผ ์ผ์นํ๋๋ฐ๋ ๊ฒฝ์ฐ์ ์์ ํฌํจX
์์ธ : left, right, sum ์ด๊ธฐ๊ฐ์ด ์๋ชป๋จ
const fs = require('fs');
const stdin = (process.platform === 'linux'
? fs.readFileSync('/dev/stdin').toString()
: `4 2
1 3 1 1`
).split('\n');
let [N, M] = stdin[0].split(' ').map(Number);
let input = stdin[1].split(' ').map(Number);
let result = 0;
let left = 0, right = 1;
let sum = input[left] + input[right];
while(left < N && right < N) {
if (sum === M) {
result++;
sum += input[++right];
}
else if (sum < M) sum += input[++right];
else if (sum > M) sum -= input[left++];
}
console.log(result);
2021-07-19 ์ฑ๊ณต, 136ms
const fs = require('fs');
const stdin = (process.platform === 'linux'
? fs.readFileSync('/dev/stdin').toString()
: `4 2
2 3 1 1`
).split('\n');
let [N, M] = stdin[0].split(' ').map(Number);
let input = stdin[1].split(' ').map(Number);
let result = 0;
let left = 0, right = 0;
let sum = input[left];
while(left < N && right < N) {
if (sum === M) {
result++;
sum += input[++right];
}
else if (sum < M) sum += input[++right];
else if (sum > M) sum -= input[left++];
}
console.log(result);