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

[ ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ(JavaScript) ] section05 - 5 - ์ตœ๋Œ€ ๋งค์ถœ

by YWTechIT 2021. 8. 27.
728x90

๐Ÿ“ section05 - 5 - ์ตœ๋Œ€ ๋งค์ถœ

์—ฐ์†๋œ K์ผ ๋™์•ˆ์˜ ์ตœ๋Œ€ ๋งค์ถœ์•ก์„ ๊ตฌํ•˜๋Š” slidingWindow ๋ฌธ์ œ์ธ๋ฐ ์—ฌ๊ธฐ์„œ ๋ฌธ์ œ์ธ ๊ฑด slidingWindow์„ ์ฒ˜์Œ ๋ฐฐ์šด๊ฒƒ์ด๋‹ค. twoPointer๋ฅผ ๋ฐฐ์› ๋‹ค๋ฉด ๋ฒ”์œ„๋ฅผ ๋งŽ์ด ๋ฒ—์–ด๋‚˜์ง€ ์•Š์•„์„œ ๋‹คํ–‰์ด์—ˆ๋‹ค. N์˜ ๋ฒ”์œ„๋Š” 100,000๊นŒ์ง€์ธ๋ฐ, ๋งŒ์•ฝ, ์‹œ๊ฐ„๋ณต์žก๋„๊ฐ€ O(N^2)์ด์—ˆ๋‹ค๋ฉด ์‹œ๊ฐ„์ดˆ๊ณผ ํŒ์ •์„ ๋ฐ›์•˜์„ ๊ฒƒ์ด๋‹ค. ๋˜๋„๋ก O(nlogn)์ด๋‚ด๋กœ ๋Š์ž.

 

์ด ๋ฌธ์ œ์˜ ํ•ต์‹ฌ ์š”์ง€๋Š”์—ฐ์†๋œ 3์ผ๊ฐ„์ธ๋ฐ, ๋‚˜๋Š” while๋ฌธ์œผ๋กœ ํˆฌ ํฌ์ธํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด์„œ rt-lt+1===k์„ ์ง€ํ‚ค๋Š” ์„ ์—์„œ ์ตœ๋Œ€๋งค์ถœ์„ ๊ณ„์‚ฐํ–ˆ๋‹ค. ๊ทธ์™€ ๋น„์Šทํ•˜๊ฒŒ ๊ฐ•์‚ฌ๋‹˜์€ for๋ฌธ์œผ๋กœ ํ‘ธ์…จ๋Š”๋ฐ, ์ด์ „์— k๋ฒˆ์งธ๊นŒ์ง€์˜ ํ•ฉ์„ ๊ตฌํ•ด๋†“๊ณ , sum์„ ๋ˆ„์ ํ•˜๋ฉด์„œ k๋ฒˆ์งธ ์ด์ „์˜ ์ธ๋ฑ์Šค๋ฅผ ๊ณ„์† ๋นผ์คฌ๋‹ค. ์ฆ‰, ์ด์ „ ๋‹จ๊ณ„+ํ˜„์žฌ ๋‹จ๊ณ„์— ์ค‘๋ณต๋˜๋Š” ์ˆ˜๋Š” ์—ฐ์‚ฐ์—์„œ ์ œ์™ธ์‹œํ‚ค๊ณ  ๋‹ค์Œ sum์— ๋ˆ„์ ๋  ์ƒˆ๋กœ์šด ๊ฐ’๊ณผ k๋ฒˆ์งธ ์ด์ „์˜ ๊ฐ’๋งŒ ์—ฐ์‚ฐ์— ํฌํ•จ์‹œํ‚ค๋Š” ๊ฒƒ์ด๋‹ค.

 

k๋ฒˆ์งธ ์ด์ „์˜ ์ธ๋ฑ์Šค๋งŒ ๋นผ์ฃผ๋Š” ์ด์œ ๋Š” ์ด์ „ index์™€ ํ˜„์žฌ index๋Š” ์ค‘๋ณต๋˜๊ธฐ ๋•Œ๋ฌธ์ธ๋ฐ, ๋งŒ์•ฝ bruteForce๋กœ ํ’€์—ˆ๋‹ค๋ฉด ์ค‘๋ณต๊ฐ’์„ ๊ณ ๋ คํ•˜์ง€ ์•Š๊ธฐ ๋•Œ๋ฌธ์— ์ด์ค‘ ๋ฐ˜๋ณต๋ฌธ์„ ์‚ฌ์šฉํ–ˆ์„ ๊ฒƒ์ด๋‹ค. bruteForce๋กœ๋„ ํ’€์–ด๋ดค๊ณ  slidingWindow๋กœ๋„ ํ’€์—ˆ๋‹ค.

 

 

728x90

 

 

// bruteForce
let n = 10;
let k = 3;
let arr = [12, 15, 11, 20, 25, 10, 20, 19, 13, 15];

for (let i=0; i<n-k+1; i++){
    let max = 0;
    for (let j=i; j<i+k; j++){
        max += arr[j]
    }
    console.log(max)
}

 

let n = 10;
let k = 3;
let arr = [12, 15, 11, 20, 25, 10, 20, 19, 13, 15];

// sliding window1 ๋‚˜์˜ ์ฝ”๋“œ
function solution(n, k, arr) {
  let lt = rt = currentSum = 0;
  let max = Number.MIN_SAFE_INTEGER;

  while (rt < n) {
    currentSum += arr[rt];
    if (rt-lt+1 === k) {
      max = Math.max(max, currentSum);
      currentSum -= arr[lt++];
    }
    rt++;
  }
  return max;
}

// sliding window2 ๊ฐ•์˜ ์ฝ”๋“œ
function solution(n, k, arr) {
  let lt = rt = currentSum = 0;
  let max = Number.MIN_SAFE_INTEGER;
  let answer;

 for (let i=0; i<k; i++) currentSum+=arr[i];
 answer = currentSum;

 for (let i=k; i<n; i++){
     currentSum+=(arr[i] - arr[i-k])
		 answer = Math.max(answer, currentSum);
 }
return answer;
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€