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

Added Maximum product of 3 numbers in an array #789

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
raklaptudirm merged 3 commits into TheAlgorithms:master from devcer:master
Oct 20, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions Dynamic-Programming/MaxProductOfThree.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* Given an array of numbers, return the maximum product
* of 3 numbers from the array
* https://wsvincent.com/javascript-three-sum-highest-product-of-three-numbers/
* @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) throw new Error('Triplet cannot exist with the given array')
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)
}
17 changes: 17 additions & 0 deletions Dynamic-Programming/tests/MaxProductOfThree.test.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { maxProductOfThree } from '../MaxProductOfThree'

describe('MaxProductOfThree', () => {
it('expects to throw error for array with only 2 numbers', () => {
expect(() => {
maxProductOfThree([1, 3])
}).toThrow('Triplet cannot exist with the given array')
})

it('expects to return 300 as the maximum product', () => {
expect(maxProductOfThree([10, 6, 5, 3, 1, -10])).toBe(300)
})

it('expects to return 300 as the maximum product', () => {
expect(maxProductOfThree([10, -6, 5, 3, 1, -10])).toBe(600)
})
})

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