[JavaScript] Easy to understand - 3 solutions
Since the integers in nums are in range [1, 10^3], the key to this problem is to find out the biggest and the second biggest number in nums.\n\n## SOLUTION 1\n\
Since the integers in `nums` are in range `[1, 10^3]`, the key to this problem is to find out the biggest and the second biggest number in `nums`.\n\n## SOLUTION 1\n\nWe use 2 variables to maintain our targets during the traversal of `nums`. It\'s pretty straight forward.\n\n```js\nconst maxProduct = nums => {\n  let m1 = 0, m2 = 0;\n  for (const val of nums) {\n    m2 = Math.max(m2, Math.min(m1, val));\n    m1 = Math.max(m1, val);\n  }\n  return (m1 - 1) * (m2 - 1);\n};\n```\n\n## SOLUTION 2\n\nWe use 2 pointers - one starts from 0 and the other one starts from `nums.length - 1` - to traversal to the middle.\n\nDuring the traversal, we maintain current biggest number in `i` or `j`. If `i` is smaller, we do `++i`. If `j` is smaller, we do `--j`.\n\nSo, when the traversal finished, we must have met this situation - the biggest number and the second biggest number have been in `i` and `j`.\n\n```js\nconst maxProduct = nums => {\n  let max = 0;\n  for (let i = 0, j = nums.length - 1; i < j;) {\n    max = Math.max(max, (nums[i] - 1) * (nums[j] - 1));\n    nums[i] < nums[j] ? ++i : --j;\n  }\n  return max;\n};\n```\n\n## SOLUTION 3\n\nWe use the `Array.prototype.reduce` to make solution 1 to an 1-line version.\n\n```js\nconst maxProduct = (nums, max = nums.reduce((prev, val) => [Math.max(prev[1], Math.min(prev[0], val)), Math.max(prev[0], val)], [0, 0])) => (max[0] - 1) * (max[1] - 1);\n```\n
['JavaScript']