題目:給定一個(gè)長度為N的整數(shù)數(shù)組蟆肆,只允許用乘法便监,不能用除法雏搂,計(jì)算任意(N-1)個(gè)數(shù)的組合中乘積最大的一組画饥。
核心代碼:
<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 { // 左邊數(shù)據(jù)疊乘
left[i] = arr[i - 1] * left[i - 1]
}
for j in stride(from: count - 1, to: 0, by: -1) { // 右邊數(shù)據(jù)疊乘
right[j] = arr[j] * right[j + 1]
}
var maxValue:Int = 1
for i in 0..<count { // 計(jì)算最大值-FlyElephant
let value = left[i] * right[i + 1]
if value > maxValue {
maxValue = value
}
}
return maxValue
}`</code></pre>
測(cè)試代碼:
<pre><code>var calculator:Calculator = Calculator() var calculatorData:[Int] = [2, 3, 4, 5, 6] var calResult:Int = calculator.multiMaxValue(arr: calculatorData) print("FlyElephant--子數(shù)組的最大乘積---\(calResult)")
</code></pre>