Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 41ddee7

Browse files
committed
Added Maximum product of 3 numbers in an array
1 parent 5f601fa commit 41ddee7

File tree

2 files changed

+52
-0
lines changed

2 files changed

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

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /