์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ธํ”„๋Ÿฐ ์„น์…˜5] ์ตœ๋Œ€ ๋งค์ถœ (Javascript)

์€์ง„ 2021. 6. 25. 15:08

์ธํ”„๋Ÿฐ

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[์ธํ”„๋Ÿฐ ์„น์…˜5] ์ตœ๋Œ€ ๋งค์ถœ (Javascript)
์œ ๋ฃŒ ๊ฐ•์˜์ธ ๊ด€๊ณ„๋กœ ๋ฌธ์ œ ์„ค๋ช…์€ ์ƒ๋žตํ•ฉ๋‹ˆ๋‹ค.


โœ๏ธIdea Sketch

2021-06-25

1. ์—ฐ์† ์ตœ๋Œ€ ๋งค์ถœ์•ก์€?

2. left์™€ right ๊ฐ„์˜ ๊ฐ„๊ฒฉ์€ k

let left = 0, right = k-1;

3. left++, right++ํ•˜๋ฉด์„œ sum ๊ตฌํ•˜๊ธฐ

4. sum์ด max๋ณด๋‹ค ๋” ํฐ์ง€ ํŒ๋‹จ

let max = Number.MIN_SAFE_INTEGER;
max = sum > max ? sum : min;  // ์ฒซ๋ฒˆ์งธ ๋ฐฉ๋ฒ•
max = Math.max(max, sum);  // ๋‘๋ฒˆ์งธ ๋ฐฉ๋ฒ•

5. ๋ฌธ์ œ์  : Math.max(max, sum) ์˜ NaN ๋ฐ˜ํ™˜

  • right๋ฅผ ์ „์œ„์—ฐ์‚ฐ์ž๋กœ ๊ณ„์‚ฐํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์ƒ๊ธฐ๋Š” ๋ฌธ์ œ
  while (right < len) {  // len์ด 10, right๊ฐ€ 9์ผ ๋•Œ ๋ฐ˜๋ณต๋ฌธ ํ†ต๊ณผ
    sum -= arr[left++];
    sum += arr[++right];  // right๋Š” 9+1, arr[10]์€ NaN, ๋”ฐ๋ผ์„œ sum์€ NaN
    max = Math.max(max, sum);  // Math.max()๊ฐ€ NaN ๋ฐ˜ํ™˜
  }
  • ํ•ด๊ฒฐ๋ฐฉ๋ฒ• : ๋ฐ˜๋ณต๋ฌธ์˜ ์ข…๋ฃŒ์กฐ๊ฑด ์ˆ˜์ •
  while (right < len-1) {
    sum -= arr[left++];
    sum += arr[++right];
    max = Math.max(max, sum);
  }


โœ๏ธ์†Œ์Šค์ฝ”๋“œ

2021-06-25

function solution(arr, k) {
  let left = 0, right = k-1;
  let sum = 0;

  for (let i=0; i<k; i++) sum += arr[i];
  let max = sum;

  while (right < arr.length) {
    sum -= arr[left++];
    sum += arr[++right];
    max = sum > max ? sum : max;
  }

  return max;
}