Skip to content

Latest commit

 

History

History
40 lines (33 loc) · 780 Bytes

1464.数组中两元素的最大乘积.md

File metadata and controls

40 lines (33 loc) · 780 Bytes

1464.数组中两元素的最大乘积

/*
 * @lc app=leetcode.cn id=1464 lang=typescript
 *
 * [1464] 数组中两元素的最大乘积
 */

// @lc code=start

function maxProduct(nums: number[]): number {}
// @lc code=end

解法 1: 枚举

function maxProduct(nums: number[]): number {
  let max = nums[0] - 1,
    res = 0
  for (let i = 1; i < nums.length; i++) {
    res = Math.max(max * (nums[i] - 1), res)
    max = Math.max(max, nums[i] - 1)
  }
  return res
}

Case

test.each([
  { input: { nums: [3, 4, 5, 2] }, output: 12 },
  { input: { nums: [1, 5, 4, 5] }, output: 16 },
  { input: { nums: [3, 7] }, output: 12 },
])('input: nums = $input.nums', ({ input: { nums }, output }) => {
  expect(maxProduct(nums)).toEqual(output)
})