mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 09:28:26 +08:00
Added Maximum product of 3 numbers in an array
This commit is contained in:
37
Dynamic-Programming/MaxProductOfThree.js
Normal file
37
Dynamic-Programming/MaxProductOfThree.js
Normal file
@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Given an array of numbers, return the maximum product
|
||||
* of 3 numbers from the array
|
||||
* @param {number[]} arrayItems
|
||||
* @returns number
|
||||
*/
|
||||
export function maxProductOfThree(arrayItems) {
|
||||
// if size is less than 3, no triplet exists
|
||||
let n = arrayItems.length
|
||||
if (n < 3) return -1
|
||||
let max1 = arrayItems[0],
|
||||
max2 = -1,
|
||||
max3 = -1,
|
||||
min1 = arrayItems[0],
|
||||
min2 = -1
|
||||
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) {
|
||||
max3 = max2
|
||||
max2 = arrayItems[i]
|
||||
} else if (max3 === -1 || arrayItems[i] > max3) {
|
||||
max3 = arrayItems[i]
|
||||
}
|
||||
if (arrayItems[i] < min1) {
|
||||
min2 = min1
|
||||
min1 = arrayItems[i]
|
||||
} else if (min2 === -1 || arrayItems[i] < min2) {
|
||||
min2 = arrayItems[i]
|
||||
}
|
||||
}
|
||||
let prod1 = max1 * max2 * max3,
|
||||
prod2 = max1 * min1 * min2
|
||||
return Math.max(prod1, prod2)
|
||||
}
|
Reference in New Issue
Block a user