Tuesday, July 16, 2019

Puzzle - Highest product of 3 numbers in an array

Highest Product of triplets in array – Algorithm

Below is a puzzle I got from a colleague when he attended an interview. Trying to solve my way.

Question

  • Find the triplet from integer array whose product is highest
  • Use single loop.
  • Language can be any

Samples

  • Input [1,2,3,4] -> [2,3,4]
  • Input [-5,-7,4,2,1,9]-> [-5,-7,9]
  • Input [-10,-3,-5,0,-20]->[-10,-5,-20]

Approach

Since 2 negative numbers can produce positive product the approach taken was to find the lowest, second lowest, third highest, second highest and first highest numbers and compared their sums as follows.

            if (lowest * secondLowest * highest > highest * secondHighest * thirdHighest)
            {
                return new int[3] { lowest, secondLowest, highest };
            }
            else
            {
                return new int[3] { thirdHighest, secondHighest, highest };
            }


Finding the numbers is the trick. One implementation can be found in below location.
https://github.com/joymon/puzzles/tree/master/Numbers/HighestProductOfTripletInArray

Comment if there are any other simple implementations.

Happy coding...

No comments: