LeetCode-628. Maximum Product of Three Numbers

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
Note:
The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.

func maximumProduct(_ nums: [Int]) -> Int {
    if nums.count < 3 {
        return 0
    }
    var nums = nums.sorted()
    let num1 = nums[nums.count - 1]
    let num2 = nums[nums.count - 2]
    let num3 = nums[nums.count - 3]
    let num4 = nums[1]
    let num5 = nums[0]
    let max1 = num1 * num2 * num3
    let max2 = num1 * num4 * num5
    return max(max1, max2)
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目 Given an integer array, find three numbers whose produ...
    Eazow阅读 189评论 0 0
  • 春暖正芳 拂叶斑斓花倩倩 眉目流转 微唇启齿笑连连 两小无猜 碧落泉下追戏闹 人生正好 与子携伴共婵娟
    房屋下的猫阅读 237评论 0 0
  • 一转眼已到九月, 想起, 去年乃至数前年的九月, 回忆起我的学校, 我的朋友们。 如今, 我们的角色已变, 希望你...
    爱听音乐的猫阅读 246评论 0 0
  • 一群鸟在空中飞着 他们选定了方向 飞往同一地方 一只小鸟脱离了 独自飞着 老鹰叫住它 信鸽叫住它 麻雀叫住它 他不...
    过非往路阅读 235评论 0 0
  • 唐梓含,狮子座,O型血,高冷,高冷,高高冷…… 林乔,水瓶座,A型血,闷骚神经质,躁动文艺男。 林乔再遇到唐梓含,...
    家旭老师阅读 421评论 0 0