code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

628 Maximum Product Of Three Numbers

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

/*
 * Given an integer array, find three numbers whose product is
 * maximum and output the maximum product.
 *
 * Example 1:
 *
 * Input: [1,2,3]
 * Output: 6
 *
 *
 * Example 2:
 *
 * Input: [1,2,3,4]
 * Output: 24
 */

function maximumProductOfThreeNumbers(value) {
  value = value.sort((a, b) => a - b)
  let maxForNeg = value[0] * value[1] * value[value.length - 1]
  let maxForPositive = value.slice(value.length - 3, value.length).reduce((t, c) => t *= c)
  return maxForNeg > maxForPositive ? maxForNeg : maxForPositive
}

test('maximum Product Of Three Numbers', () => {
  expect(maximumProductOfThreeNumbers([1, 2, 3, 4])).toEqual(24)
})

Created 2020-04-18T21:15:24+00:00 · Edit