题目:给定一个长度为N的整数数组,只允许用乘法,不能用除法,计算任意(N-1)个数的组合中乘积最大的一组。
核心代码:
<pre><code>` func multiMaxValue(arr:[Int]) -> Int {
let count:Int = arr.count
var left:[Int] = [Int].init(repeating: 1, count: count)
var right:[Int] = [Int].init(repeating: 1, count: count + 1)
for i in 1..<count { // 左边数据叠乘
left[i] = arr[i - 1] * left[i - 1]
}
for j in stride(from: count - 1, to: 0, by: -1) { // 右边数据叠乘
right[j] = arr[j] * right[j + 1]
}
var maxValue:Int = 1
for i in 0..<count { // 计算最大值-FlyElephant
let value = left[i] * right[i + 1]
if value > maxValue {
maxValue = value
}
}
return maxValue
}`</code></pre>
测试代码:
<pre><code>var calculator:Calculator = Calculator() var calculatorData:[Int] = [2, 3, 4, 5, 6] var calResult:Int = calculator.multiMaxValue(arr: calculatorData) print("FlyElephant--子数组的最大乘积---\(calResult)")
</code></pre>
网友评论