DEV Community

loading...

Algorithm 101: 2 Ways to Find the Largest Product Yielded by 3 Integers

ebereplenty profile image NJOKU SAMSON EBERE ・2 min read

This article will be showing us 2 Ways to Find the Largest Product of a given array of numbers. It is a new week over here and I want to begin this article by asking you:

How are you dealing with COVID-19 in you area?

I hope you are staying safe and taking preventive measures?

I want you to keep this in mind:

"This too shall pass and I want you to be here when it has passed"

How can we find Largest Product?


largestProduct([5, 3, 4, 1, 2]); // 60

largestProduct([-10, 7, 29, 30, 5, -10, -70]); // 21000

Enter fullscreen mode Exit fullscreen mode

The trick is simple. It is either of the following:

max1 * max2 * max3 

OR

min1 * min2 * max1

Prerequisite

To flow with this article, it is expected that you have basic understanding of javascript's Math methods and array methods.

Let's find the largest product using:

  • ternary operator, .sort()
      function largestProduct(array) {
        let desSort = array.sort((a, b) => b - a);

        // min1 * min2 * max1
        let productA =
          desSort[desSort.length - 1] *
          desSort[desSort.length - 2] *
          desSort[0];

        // max1 * max2 * max3
        let productB = desSort[0] * desSort[1] * desSort[2];

        return productA > productB ? productA : productB;
      }
Enter fullscreen mode Exit fullscreen mode
  • for...loop, ternary operator, if... statement, .sort()
      function largestProduct(array) {
        let desSort = array.sort((a, b) => b - a);
        let productA = 1;
        let productB = 1;

        // min1 * min2 * max1
        for (let i = desSort.length - 2; i < desSort.length; i++) {
          productA = productA * desSort[i];
        }
        productA = productA * desSort[0];

        // max1 * max2 * max3
        for (let i = 0; i <= desSort.length; i++) {
          productB = productB * desSort[i];
          if (i === 2) break;
        }

        return productA > productB ? productA : productB;
      }
Enter fullscreen mode Exit fullscreen mode

Conclusion

There are many ways to solve problems programmatically. You are only limited by your imagination. Feel free to let me know other ways you solved yours in the comment section.

If you have questions, comments or suggestions, please drop them in the comment section.

You can also follow and message me on social media platforms.

Twitter | LinkedIn | Github

Thank You For Your Time.

Discussion (0)

pic
Editor guide