Data Structure & Algorithm

[์•Œ๊ณ ๋ฆฌ์ฆ˜-JS] ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„ (Sliding Window) - ์—ฐ์† ์ตœ๋Œ€ ๋งค์ถœ

fnow 2022. 5. 3. 22:30
๋ฐ˜์‘ํ˜•
๐Ÿ’ก ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„
ํฌ๊ธฐ๊ฐ€ ๊ณ ์ •๋œ ํ”„๋ ˆ์ž„์ด ์ขŒ์šฐ๋กœ ์›€์ง์ด๋ฉด์„œ ํ”„๋ ˆ์ž„ ์•ˆ์— ์žˆ๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์ด์šฉํ•ด ๊ณ„์‚ฐํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜

 

๋ฌธ์ œ

N์ผ ๋™์•ˆ์˜ ๋งค์ถœ์•ก์„ ์ž…๋ ฅ ๋ฐ›์œผ๋ฉด ์—ฐ์†๋œ K์ผ ๋™์•ˆ ์ตœ๋Œ€ ๋งค์ถœ์•ก์ด ์–ผ๋งˆ์ธ์ง€ ๊ตฌํ•˜์‹œ์˜ค.

 

์ž…๋ ฅ ์˜ˆ์ œ

10 3

10 25 11 20 15 12 20 10 22 18

 

์ถœ๋ ฅ ์˜ˆ์ œ

56

 

 

ํ’€์ด

 

function solution(n, m, a) {
  let answer = sum = 0;
  
  // ์ฒ˜์Œ 3๊ฐœ ๋”ํ•˜๊ธฐ
  for (let i = 0; i < m; i++) sum += a[i];
  
  answer = sum;
  
  // ์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„
  for (let i = m; i < a.length; i++) {
    // i๋ฒˆ์งธ + i์—์„œ 4๋ฒˆ์งธ ์•ž์— ์žˆ๋Š” ์š”์†Œ ๋นผ๊ธฐ
    sum += (a[i] - a[i-m]);
    answer = Math.max(answer, sum);
  }
  
  return answer;
}

 

 

๋ฐ˜์‘ํ˜•