TheAlgorithms/JavaScript

[BUG]: MaxProductOfThree not working properly

Xolvez opened this issue · 1 comments

Description

The maxProductOfThree-function in Dynamic-Programming/MaxProductOfThree.js is not working properly when the values of the array vary around 0.

I noticed something seemed off when I looked at the code for the function, and decided to test the function using random arrays of length 4, where the values varied between -3 and 3. The output was compared to the output of a function that calculated all possible products of 3 numbers in the array, and indeed the function produced incorrect outputs.

Examples arrays that produce incorrect output:
[-2,1,-1,1]: expected = 2, actual = -1.
[-3,0,-1,1]: expected = 3, actual = 0.
[-1,1,-1,1]: expected = 1, actual = -1.

Expected Behavior

The expected behavior of the function is to find the largest product that can be produced from 3 numbers of an array. Due to the implementation, it is currently not.

Expected output of the following arrays of length 4:
[-2,1,-1,1]: expected = 2.
[-3,0,-1,1]: expected = 3.
[-1,1,-1,1]: expected = 1.

Actual Behavior

Actual output of the arrays above:
[-2,1,-1,1]: actual = -1.
[-3,0,-1,1]: actual = 0.
[-1,1,-1,1]: actual = -1.

Steps to reproduce (if applicable)

  1. Call the function maxProductOfThree with the input [-2, 1, -1, 1].
  2. Observe that the expected output is clearly 2, since (-2) * (-1) * 1 = 2
  3. Observe that the actual output is -1.

Additional information

I suspect this has to do with the way the max and min variables are initialized to -1 in the function, instead of setting them to null to begin with.

I am currently working on a fix for this, just formating the code to comply with standardjs at the moment.