Problem Solution/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/JS] ์ตœ๋Œ“๊ฐ’ ๋งŒ๋“ค๊ธฐ (2)

yuri lee 2023. 9. 22. 18:30
๋ฐ˜์‘ํ˜•

Problem Description

์ •์ˆ˜ ๋ฐฐ์—ด numbers๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์ง‘๋‹ˆ๋‹ค. numbers์˜ ์›์†Œ ์ค‘ ๋‘ ๊ฐœ๋ฅผ ๊ณฑํ•ด ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ์ตœ๋Œ“๊ฐ’์„ returnํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

Restrictions.

  • -10,000 ≤ numbers์˜ ์›์†Œ ≤ 10,000
  • 2 ≤ numbers ์˜ ๊ธธ์ด ≤ 100.

 

Input/Output Example

  • ์ž…์ถœ๋ ฅ ์˜ˆ #1 ๋‘ ์ˆ˜์˜ ๊ณฑ์ค‘ ์ตœ๋Œ“๊ฐ’์€ -3 * -5 = 15 ์ž…๋‹ˆ๋‹ค.
  • ์ž…์ถœ๋ ฅ ์˜ˆ #2  ๋‘ ์ˆ˜์˜ ๊ณฑ์ค‘ ์ตœ๋Œ“๊ฐ’์€ 10 * 24 = 240 ์ž…๋‹ˆ๋‹ค.

 

My solution

function solution(numbers) {
    numbers.sort((a, b) => a - b);
    const length = numbers.length;

    const positive = numbers[length - 1] * numbers[length - 2];
    const negative = numbers[0] * numbers[1];
    return Math.max(positive, negative);
}

 

Another solutions

function solution(numbers) {
    numbers.sort((a, b) => a - b);
    return Math.max(numbers[0]*numbers[1], numbers[numbers.length-1]*numbers[numbers.length-2]);
}

https://school.programmers.co.kr/learn/courses/30/lessons/120862

๋ฐ˜์‘ํ˜•