avatar
Published on

Codility - Max Product of Three

Author
  • avatar
    Name
    yceffort

Max Product of Three

๋ฌธ์ œ

๊ธธ์ด N์ธ ๋ฐฐ์—ด A๊ฐ€ ์ฃผ์–ด์กŒ์„๋•Œ, ์ž„์˜๋กœ ์„ธ๊ฐœ์˜ ์ˆซ์ž๋ฅผ ๊ณฑํ–ˆ์„ ๋•Œ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๋ฐฐ์—ด์˜ Index๋ฅผ ๋ฆฌํ„ดํ•ด๋ผ.

A[0] = -3
A[1] = 1
A[2] = 2
A[3] = -2
A[4] = 5
A[5] = 6

2, 4, 5๋ฒˆ์งธ๋ฅผ ๊ณฑํ•˜๋ฉด 60์„ ๋งŒ๋“ค์ˆ˜ ์žˆ๊ณ  ์ด๊ฒƒ์ด ๊ฐ€์žฅ ํฐ ๊ฒฝ์šฐ ์ด๋ฏ€๋กœ, 60์„ ๋ฆฌํ„ดํ•˜๋ฉด๋œ๋‹ค.

ํ’€์ด

function solution(A) {
  const sorted = A.sort((a, b) => a - b)
  const size = sorted.length

  let biggest = 0

  biggest = sorted[size - 1] * sorted[size - 2] * sorted[size - 3]

  if (sorted[0] < 0 && sorted[1] < 0 && sorted[size - 1] > 0) {
    const possible = sorted[0] * sorted[1] * sorted[size - 1]

    if (possible > biggest) {
      biggest = possible
    }
  }

  return biggest
}

ํ•˜๋‚˜ ์กฐ์‹ฌํ•ด์•ผ ํ•  ๊ฒƒ์€, ๋‘ ๊ฐœ์˜ ์Œ์ˆ˜ * ํ•œ๊ฐœ์˜ ์–‘์ˆ˜ ์กฐํ•ฉ์œผ๋กœ๋„ ํฐ ์ˆ˜๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค. ๋”ฐ๋ผ์„œ ๋ฌด์กฐ๊ฑด ํฐ ๊ฐ’ ์„ธ๊ฐœ๋ฅผ ๊ณฑํ•ด๋ฒ„๋ฆฌ๋ฉด ์•ˆ๋œ๋‹ค. ๋”ฐ๋ผ์„œ ๊ฐ€์žฅ ํฐ ์ˆ˜๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋Š” ์•„๋ž˜์™€ ๊ฐ™๋‹ค.

  • ์ˆซ์ž๊ฐ€ ํฐ ์ˆœ์„œ๋Œ€๋กœ ์„ธ๊ฐœ๋ฅผ ๊ณฑํ•˜๊ฑฐ๋‚˜
  • ์Œ์ˆ˜์ดํ•˜์˜ ๊ฐ€์žฅ ์ž‘์€ ์ˆซ์ž ๋‘๊ฐœ๋ฅผ ๊ณฑํ•˜๊ณ  ๊ฐ€์žฅ ํฐ ์–‘์ˆ˜๋ฅผ ๊ณฑํ•˜๊ฑฐ๋‚˜

๋˜ ํ•˜๋‚˜ ์กฐ์‹ฌํ•ด์•ผํ•  ๊ฒƒ์€, sort()๋‹ค. ๊ทธ๋ƒฅ ์•„๋ฌด ํ•จ์ˆ˜ ์—†์ด sortํ–ˆ๋”๋‹ˆ, ์ œ๋Œ€๋กœ ์ •๋ ฌํ•˜์ง€ ๋ชปํ–ˆ๋‹ค. (์กธ์•„์„œ ๊ทธ๋Ÿฐ๊ฑฐ๋ผ๊ณ  ์น˜์ž)

compareFunction์ด ์ œ๊ณต๋˜์ง€ ์•Š์œผ๋ฉด ์š”์†Œ๋ฅผ ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜ํ•˜๊ณ  ์œ ๋‹ˆ ์ฝ”๋“œ ์ฝ”๋“œ ํฌ์ธํŠธ ์ˆœ์„œ๋กœ ๋ฌธ์ž์—ด์„ ๋น„๊ตํ•˜์—ฌ ์ •๋ ฌ๋ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด "๋ฐ”๋‚˜๋‚˜"๋Š” "์ฒด๋ฆฌ"์•ž์—์˜ต๋‹ˆ๋‹ค. ์ˆซ์ž ์ •๋ ฌ์—์„œ๋Š” 9๊ฐ€ 80๋ณด๋‹ค ์•ž์— ์˜ค์ง€๋งŒ ์ˆซ์ž๋Š” ๋ฌธ์ž์—ด๋กœ ๋ณ€ํ™˜๋˜๊ธฐ ๋•Œ๋ฌธ์— "80"์€ ์œ ๋‹ˆ ์ฝ”๋“œ ์ˆœ์„œ์—์„œ "9"์•ž์—์˜ต๋‹ˆ๋‹ค.

ํ•œ๊ตญ ๋ง์ด ๋” ์–ด๋ ต๋‹ค (....)

If compareFunction is not supplied, all non-undefined array elements are sorted by converting them to strings and comparing strings in UTF-16 code units order. For example, "banana" comes before "cherry". In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. All undefined elements are sorted to the end of the array.

๋น„๊ต ํ•จ์ˆ˜๊ฐ€ ์ •์˜ ๋˜์ง€ ์•Š๋Š”๋‹ค๋ฉด, ๋ชจ๋“  ์š”์†Œ๋ฅผ string์œผ๋กœ ๋ณ€ํ™˜ํ•˜๊ณ  ์ด string์„ UTF-16 ์ฝ”๋“œ๋กœ ๋ณ€ํ™˜ํ•ด์„œ ๋น„๊ต ํ•œ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.

const a = [-1, -10, -9, -5, -7]
const sorted = a.sort()
console.log(sorted) // [-1, -10, -5, -7, -9]]

์ˆซ์ž ๋น„๊ต ์‹œ์—๋Š” ์ ˆ๋Œ€ compareFunction์„ ๋น„์šฐ์ง€๋ง์ž -

์ถœ์ฒ˜

https://app.codility.com/demo/results/trainingCGB84G-ST8/