Skip to content

Commit 358b199

Browse files
authored
chore: Merge pull request TheAlgorithms#789 from devcer/master
Added Maximum product of 3 numbers in an array
2 parents a9d2051 + 67ec915 commit 358b199

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* Given an array of numbers, return the maximum product
3+
* of 3 numbers from the array
4+
* https://wsvincent.com/javascript-three-sum-highest-product-of-three-numbers/
5+
* @param {number[]} arrayItems
6+
* @returns number
7+
*/
8+
export function maxProductOfThree(arrayItems) {
9+
// if size is less than 3, no triplet exists
10+
let n = arrayItems.length
11+
if (n < 3) throw new Error('Triplet cannot exist with the given array')
12+
let max1 = arrayItems[0],
13+
max2 = -1,
14+
max3 = -1,
15+
min1 = arrayItems[0],
16+
min2 = -1
17+
for (let i = 1; i < n; i++) {
18+
if (arrayItems[i] > max1) {
19+
max3 = max2
20+
max2 = max1
21+
max1 = arrayItems[i]
22+
} else if (max2 === -1 || arrayItems[i] > max2) {
23+
max3 = max2
24+
max2 = arrayItems[i]
25+
} else if (max3 === -1 || arrayItems[i] > max3) {
26+
max3 = arrayItems[i]
27+
}
28+
if (arrayItems[i] < min1) {
29+
min2 = min1
30+
min1 = arrayItems[i]
31+
} else if (min2 === -1 || arrayItems[i] < min2) {
32+
min2 = arrayItems[i]
33+
}
34+
}
35+
let prod1 = max1 * max2 * max3,
36+
prod2 = max1 * min1 * min2
37+
return Math.max(prod1, prod2)
38+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { maxProductOfThree } from '../MaxProductOfThree'
2+
3+
describe('MaxProductOfThree', () => {
4+
it('expects to throw error for array with only 2 numbers', () => {
5+
expect(() => {
6+
maxProductOfThree([1, 3])
7+
}).toThrow('Triplet cannot exist with the given array')
8+
})
9+
10+
it('expects to return 300 as the maximum product', () => {
11+
expect(maxProductOfThree([10, 6, 5, 3, 1, -10])).toBe(300)
12+
})
13+
14+
it('expects to return 300 as the maximum product', () => {
15+
expect(maxProductOfThree([10, -6, 5, 3, 1, -10])).toBe(600)
16+
})
17+
})

0 commit comments

Comments
 (0)