๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๋ฌธ์ œํ’€์ด/Programmers - Lv.1

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Lv.1] ์ตœ์†Œ์ง์‚ฌ๊ฐํ˜•

ํ’€์ด ๋‚ ์งœ : 2025.04.25
๋ฌธ์ œ ์œ ํ˜• : ์™„์ „ํƒ์ƒ‰
๋ฌธ์ œ ์ œ๋ชฉ : ์ตœ์†Œ์ง์‚ฌ๊ฐํ˜•
๋ฌธ์ œ ๋งํฌ : https://school.programmers.co.kr/learn/courses/30/lessons/86491

Intuition

  • ๋ช…ํ•จ์˜ ๊ฐ€๋กœ,์„ธ๋กœ ํฌ๊ธฐ๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด์ด ์ฃผ์–ด์งˆ ๋•Œ, ๋ชจ๋“  ๋ช…ํ•จ์„ ๋‹ด์„ ์ˆ˜ ์žˆ๋Š” ์ง€๊ฐ‘์˜ ํฌ๊ธฐ๋ฅผ ๊ตฌํ•ด์•ผ ํ•œ๋‹ค.
    • ๊ฐ ๋ช…ํ•จ์€ ํšŒ์ „์ด ๊ฐ€๋Šฅํ•˜๋‹ค. (๊ฐ€๋กœ, ์„ธ๋กœ๋ฅผ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๋‹ค.)
  • ๊ฐ ๋ช…ํ•จ๋งˆ๋‹ค ๊ธด ์ชฝ์€ ๊ฐ€๋กœ์—, ์งง์€ ์ชฝ์€ ์„ธ๋กœ์— ๋‘”๋‹ค๊ณ  ์ƒ๊ฐํ•ด๋ณด๋ฉด, ๊ธด ์ชฝ ์ค‘์— ์ตœ๋Œ“๊ฐ’๊ณผ ์งง์€ ์ชฝ ์ค‘์— ์ตœ๋Œ“๊ฐ’์„ ๊ตฌํ•˜๋ฉด ๋ชจ๋“  ๋ช…ํ•จ์„ ๋‹ค ๋„ฃ์„ ์ˆ˜ ์žˆ๋‹ค.
    • ๋ฌธ์ œ ์œ ํ˜•์€ ์™„์ „ํƒ์ƒ‰(Brute force)๋ผ๊ณ  ๋˜์–ด ์žˆ์ง€๋งŒ, ๋ช…ํ•จ์„ ํšŒ์ „ํ•œ ๋ชจ๋“  ์กฐํ•ฉ์„ ์‹œ๋„ํ•˜์ง€ ์•Š๊ณ  ๊ทธ๋ฆฌ๋”” ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ํ‘ธ๋Š” ๊ฒŒ ๋” ํšจ์œจ์ ์ผ ๊ฒƒ ๊ฐ™๋‹ค.

Approach

  • ๋ช…ํ•จ ํฌ๊ธฐ์—์„œ ํฐ ์ชฝ์˜ ๊ธธ์ด๋ฅผ ๋‹ด์„ ๋ฐฐ์—ด(longs), ์ž‘์€ ์ชฝ์˜ ๊ธธ์ด๋ฅผ ๋‹ด์„ ๋ฐฐ์—ด(shorts)์„ ์„ ์–ธํ•œ๋‹ค.
  • sizes๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ ํฐ ์ชฝ์˜ ๊ธธ์ด๋ฅผ longs, ์ž‘์€ ์ชฝ์˜ ๊ธธ์ด๋ฅผ shorts์— ๋‹ด๋Š”๋‹ค.
  • longs์˜ ์ตœ๋Œ“๊ฐ’, shorts์˜ ์ตœ๋Œ“๊ฐ’์„ ๊ณฑํ•œ ๊ฐ’(= ์ง€๊ฐ‘์˜ ์ตœ๋Œ€ ํฌ๊ธฐ)๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

Complexity

  • Time complexity : O(n)
    • sizes์˜ ํฌ๊ธฐ๋ฅผ n์ด๋ผ๊ณ  ํ•  ๋•Œ sizes๋ฅผ ์ˆœํšŒํ•˜๋ฏ€๋กœ O(n)์ด๋‹ค.
  • Splace complexity : O(n)
    • longs, shorts ์ถ”๊ฐ€ ๋ฐฐ์—ด์„ ์ƒ์„ฑํ–ˆ๊ณ  ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋Š” ๊ฐ๊ฐ n์ด๋ฏ€๋กœ O(n)์ด๋‹ค.

Code (JS)

function solution(sizes) {
    const longs = [];
    const shorts = [];

    for (const size of sizes) {
        longs.push(Math.max(...size));
        shorts.push(Math.min(...size));
    }

    return Math.max(...longs) * Math.max(...shorts);
}