Algorithm #07 - "Largest Product Of Three"

filoscoderยท2020๋…„ 1์›” 2์ผ
0

Toy Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
7/7
post-thumbnail

๐Ÿ‡บ๐Ÿ‡ธ Write a function that finds the largest possible product of the highest three numbers from an array.

  • Advance : Make your function handle negative numbers.

๐Ÿ‡ฆ๐Ÿ‡ท Escriba una funciรณn que encuentre el producto mรกximo de los tres nรบmeros mรกs grandes de una lista de numeros.

  • Advance : Haz que tu funciรณn pueda lidiar con nรบmeros negativos.

๐Ÿ‡ฐ๐Ÿ‡ท ๋ฐฐ์—ด์—์„œ ๊ฐ€์žฅ ํฐ ์„ธ ์ˆซ์ž์˜ ๊ฐ€๋Šฅํ•œ ์ตœ๋Œ€ ๊ณฑ์ˆ˜๋ฅผ ์ฐพ๋Š” ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•˜์‹ญ์‹œ์˜ค.

  • Advance : ์ž‘์„ฑ๋œ ํ•จ์ˆ˜๊ฐ€ ์Œ์ˆ˜๋„ ์ฒ˜๋ฆฌํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•˜์‹ญ์‹œ์˜ค.

Example:

// Test
const test = largestProductOfThree([2, 1, 3, -4])
// output
console.log(test); // 6

# START [ here ] ๐Ÿ

var largestProductOfThree = function(array) {
  // Your CODE
  
};

// Test
largestProductOfThree([2, 1, 3, 7]) // -> 42
largestProductOfThree([2, 5, 13, 7, 11, 3 ]) // -> 1001
largestProductOfThree([7, 5, 3, 2, -11, -13 ]) // -> 105
largestProductOfThree([-31, 34, -37, -17, 41, 19 ]) // -> 40426
largestProductOfThree([40, -50, 20, 5, 30]) // -> 24000

# Javascript solution ๐Ÿ†

  • Run it on your browser console window (F12) ๐Ÿ–ฅ
  • Please feel free to add your preference language solution ๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘งโ€๐Ÿ‘ฆ
  • Do your best to complete the problem ๐ŸŽญ
  • if you can't beat this the solution is below ๐Ÿ˜ฑ

Solution ๐Ÿ‘‡

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

var largestProductOfThree = function(array) {
  // TODO: everything
  const sorted = array.sort((a, b) => {
    return b - a;
  });
  // variable called "result" with value 1
  let result = 1;
  // if(sorted is not empty)
  // iterate over "sorted", multiply first three element with "result" accumulative
  for (let i = 0; i < 3; i++) {
    if (sorted[i] < 0) {
      // if(sorted[i] is a NEGATIVE number)
      result = result * Math.abs(sorted[i]);
    } else {
      // if(sorted[i] is a POSITIVE number)
      result = result * sorted[i];
    }
  }
  return result;
};
profile
Keep thinking code should be altruistic

0๊ฐœ์˜ ๋Œ“๊ธ€