Skip to content

Instantly share code, notes, and snippets.

@alireza-mpr
Last active November 15, 2020 02:47
Show Gist options
  • Save alireza-mpr/10869e1020a6a6f5344247d7e4ea0da0 to your computer and use it in GitHub Desktop.
Save alireza-mpr/10869e1020a6a6f5344247d7e4ea0da0 to your computer and use it in GitHub Desktop.
/*
Sort A [a1..aN] where a1 <= aN. Then:
Case 1: A=[+, +, ..., +] || A=[-, -, ..., -] => Max = Product of the last three elements
Case 2: N= 3 => Only one product exists
Case 3: A=[-, -, ...., +] => Max = Product of the first and the last two elements
*/
function solution(A) {
let N = A.length;
A.sort((a,b) => (a-b));
return Math.max(A[0] * A[1] * A[N - 1], A[N - 1] * A[N - 2] * A[N - 3]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment