Last active
April 5, 2016 21:50
-
-
Save thaibui/c6b5c04f8fa3d0dcb341db6361bab435 to your computer and use it in GitHub Desktop.
A function that compute the max positive product of 3 intergers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Write a function which takes in an array of integers and returns the highest positive product | |
possible by multiplying 3 distinct numbers. NO SORTING is ALLOWED | |
example: | |
[1, 3, 5, 2, 8, 0, -1, 3] | |
=> 8 * 5 * 3 = 120 | |
[0, -1, 3, 100, -70, -5] | |
=> -70*-50*100=350000 | |
*/ | |
var a = [1,3,5,2,8,0,-1,3] | |
//a = [0,-1,3,100,-70,-5] | |
//a = [3,-3,-3,-3,-3,-3,-1,-3] | |
function maxPossitiveProduct(a){ | |
var n = a.length; | |
var p3rd = 0, p2nd = 0, p1st = 0; | |
var n1st = 0, n2nd = 0; | |
var q,u,v; | |
for(var i = 0; i < n; i++){ | |
// possitive cases | |
if (a[i] > p1st){ | |
p3rd = p2nd; | |
p2nd = p1st; | |
p1st = a[i]; | |
} else if (a[i] > p2nd && a[i] != p1st){ | |
p3rd = p2nd; | |
p2nd = a[i]; | |
} else if(a[i] > p3rd && a[i] != p1st && a[i] != p2nd) { | |
p3rd = a[i]; | |
} else | |
// negative cases | |
if (a[i] < n1st){ | |
n2nd = n1st; | |
n1st = a[i]; | |
} else if (a[i] < n2nd && a[i] != n1st) { | |
n2nd = a[i]; | |
} | |
} | |
if(n1st * n2nd > p2nd * p3rd){ | |
q = n1st; | |
u = n2nd; | |
v = p1st; | |
} else { | |
q = p1st; | |
u = p2nd; | |
v = p3rd; | |
} | |
return [q,u,v]; | |
} | |
r = maxPossitiveProduct(a); | |
var max = r[0] * r[1] * r[2]; | |
if(max == 0){ | |
console.log("No result found."); | |
} else { | |
console.log("Max: " + max + " Combination: " + r[0] + " " + r[1] + " " + r[2]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment