mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-04 15:39:42 +08:00
fix: fixed error in the MaxProductOfThree algorithm (#1295)
* fix: fixed error in the MaxProductOfThree algorithm Fixed the error in the MaxProductOfThree by initializing the max and min variables to null instead of -1. The checks were then altered to check for null instead of -1. Also wrote more tests, which randomly generated small arrays and compared the output of the maxProductOfThree-algorithm to the output of a slower, but complete, function which calculates all posible triple-products of the values of the array. Fixes: #1294 * fix: Added newlines at the end of the files
This commit is contained in:
@ -10,25 +10,25 @@ export function maxProductOfThree (arrayItems) {
|
||||
const n = arrayItems.length
|
||||
if (n < 3) throw new Error('Triplet cannot exist with the given array')
|
||||
let max1 = arrayItems[0]
|
||||
let max2 = -1
|
||||
let max3 = -1
|
||||
let max2 = null
|
||||
let max3 = null
|
||||
let min1 = arrayItems[0]
|
||||
let min2 = -1
|
||||
let min2 = null
|
||||
for (let i = 1; i < n; i++) {
|
||||
if (arrayItems[i] > max1) {
|
||||
max3 = max2
|
||||
max2 = max1
|
||||
max1 = arrayItems[i]
|
||||
} else if (max2 === -1 || arrayItems[i] > max2) {
|
||||
} else if (max2 === null || arrayItems[i] > max2) {
|
||||
max3 = max2
|
||||
max2 = arrayItems[i]
|
||||
} else if (max3 === -1 || arrayItems[i] > max3) {
|
||||
} else if (max3 === null || arrayItems[i] > max3) {
|
||||
max3 = arrayItems[i]
|
||||
}
|
||||
if (arrayItems[i] < min1) {
|
||||
min2 = min1
|
||||
min1 = arrayItems[i]
|
||||
} else if (min2 === -1 || arrayItems[i] < min2) {
|
||||
} else if (min2 === null || arrayItems[i] < min2) {
|
||||
min2 = arrayItems[i]
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user