FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
JavaScript/Dynamic-Programming/MaxProductOfThree.js at master · TheAlgorithms/JavaScript · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
TheAlgorithms
/
JavaScript
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
5.8k
Star
34.2k
Code
Issues
21
Pull requests
192
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
JavaScript
/
Dynamic-Programming
/
MaxProductOfThree.js
Copy path
More file actions
More file actions
Latest commit
History
History
History
38 lines (38 loc) · 1.1 KB
Breadcrumbs
JavaScript
/
Dynamic-Programming
/
MaxProductOfThree.js
Copy path
File metadata and controls
38 lines (38 loc) · 1.1 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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
const
n
=
arrayItems
.
length
if
(
n
<
3
)
throw
new
Error
(
'Triplet cannot exist with the given array'
)
let
max1
=
arrayItems
[
0
]
let
max2
=
null
let
max3
=
null
let
min1
=
arrayItems
[
0
]
let
min2
=
null
for
(
let
i
=
1
;
i
<
n
;
i
++
)
{
if
(
arrayItems
[
i
]
>
max1
)
{
max3
=
max2
max2
=
max1
max1
=
arrayItems
[
i
]
}
else
if
(
max2
===
null
||
arrayItems
[
i
]
>
max2
)
{
max3
=
max2
max2
=
arrayItems
[
i
]
}
else
if
(
max3
===
null
||
arrayItems
[
i
]
>
max3
)
{
max3
=
arrayItems
[
i
]
}
if
(
arrayItems
[
i
]
<
min1
)
{
min2
=
min1
min1
=
arrayItems
[
i
]
}
else
if
(
min2
===
null
||
arrayItems
[
i
]
<
min2
)
{
min2
=
arrayItems
[
i
]
}
}
const
prod1
=
max1
*
max2
*
max3
const
prod2
=
max1
*
min1
*
min2
return
Math
.
max
(
prod1
,
prod2
)
}
Back
|
FazBrowse Home
|
New Git URL