๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/์ธํ”„๋Ÿฐ(inflearn)

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] 20 - ์ ์ˆ˜ ๊ณ„์‚ฐ

by YWTechIT 2021. 8. 13.
728x90

๐Ÿ“ 20 - ์ ์ˆ˜ ๊ณ„์‚ฐ

๋ฌธ์ œ์˜ ์–‘์€ ๊ธธ์ง€๋งŒ ์กฐ๊ธˆ๋งŒ ์ƒ๊ฐํ•˜๋ฉด ๊ธˆ๋ฐฉ ํ’€ ์ˆ˜ ์žˆ๋‹ค. ์—ฌ๊ธฐ์„œ ์ค‘์š”ํ•œ ์ ์€ ๊ฐ€์‚ฐ์ ์ฒ˜๋ฆฌ์ธ๋ฐ, ์—ฐ์†์œผ๋กœ ๋งž์€ ๊ฒฝ์šฐ์—๋งŒ +1์”ฉ ์ฆ๊ฐ€ํ•˜๊ฒŒ ์ž‘์„ฑํ•ด์•ผํ•œ๋‹ค.

let n = 10;
let scores = [1, 0, 1, 1, 1, 0, 0, 1, 1, 0];
console.log(solution(n, scores));

// ์‚ผํ•ญ์—ฐ์‚ฐ์ž
function solution(n, scores) {
  let extraPoint = 0;
  let cnt = 0;

  for (let score of scores) {
    score === 1 ? (extraPoint++, (cnt += extraPoint)) : (extraPoint = 0);
  }

  return cnt;
}

// if - else
function solution(n, scores) {
  let extraPoint = 0;
  let cnt = 0;

  for (let score of scores) {
    if (score === 1) {
      extraPoint++;
      cnt += extraPoint;
    } else extraPoint = 0;
  }

  return cnt;
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€