【问题标题】:Resolving highest product in an array swift快速解决数组中的最高乘积
【发布时间】:2019-11-20 13:00:04
【问题描述】:

我有一项工作是在 Ints 数组中获得最高的产品。

给定一个整数数组,找出你能从中得到的最高乘积 三个整数。如果数组大小小于 3,请打印输出 -1

这是我尝试返回的20

func adjacentElementsProduct(inputArray: [Int]) -> Int {
    let sorted = inputArray.sorted()
    let count = sorted.count
    if count > 1 {
        return max(sorted[0] * sorted[1] * sorted[2], sorted[count - 1] * sorted[count - 2] * sorted[count - 3])
    } else {
        return sorted.first ?? 0
    }
}

adjacentElementsProduct(inputArray: [3, 1, 2, 5, 4])

这个测试用例怎么会失败

adjacentElementsProduct(inputArray: [1, 10, -5, 1, -100]) 

它返回 500 并且预期为 5000

【问题讨论】:

标签: swift


【解决方案1】:
func adjacentElementsProduct(inputArray: [Int]) -> Int {
    let sorted = inputArray.sorted()

    let count = sorted.count

    guard count >= 3 else {
        return -1
    }

    return max(
       sorted[count - 1] * sorted[count - 2] * sorted[count - 3],
       sorted[count - 1] * sorted[0] * sorted[1]
    )
}

它是如何工作的?

需要考虑三种情况。最高的产品是

  1. 3 个最高正数的乘积
  2. 最大正数乘以两个最小负数的乘积(负数抵消)
  3. 如果只有负数,则为 3 个最小负数的乘积。

sorted[count - 1] * sorted[count - 2] * sorted[count - 3] 涵盖了案例 1 和 3。案例2被sorted[count - 1] * sorted[0] * sorted[1]覆盖。

【讨论】:

  • 除非我弄错了,那是(现在)@King 发布的内容。
  • @MartinR 是的,因为我是在没有测试的情况下编写的,所以我对排序的方向感到困惑。
【解决方案2】:
func adjacentElementsProduct(inputArray: [Int]) -> Int {
    let sorted = inputArray.sorted()
    let count = sorted.count
    if count < 3 {
        return -1
    } else {
        return max(sorted[0] * sorted[1] * sorted[count - 1],
        sorted[count - 1] * sorted[count - 2] * sorted[count - 3])
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 2011-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多