mem
以及它是否作为
inout
. 你的问题是
runningTotal
参数我删除了该参数以匹配链接中指定的算法,现在它返回正确的结果。
var mem = [[Int]]()
func dynamicMotivation (_ wines: [Int] ) -> Int {
mem = Array(repeating: Array(repeating: 0, count: wines.count), count: wines.count)
return motivationD(wines, year: 1, ptr1: 0, ptr2: wines.count - 1)
}
func motivationD(_ wines: [Int], year: Int, ptr1: Int, ptr2: Int) -> Int {
if (ptr1 > ptr2) { return 0 }
if mem[ptr1][ptr2] != 0 {
return mem[ptr1][ptr2]
}
let maxProfit = max(
motivationD(wines, year: year + 1, ptr1: ptr1 + 1, ptr2: ptr2) + year * wines[ptr1]
,
motivationD(wines, year: year + 1, ptr1: ptr1, ptr2: ptr2 - 1) + year * wines[ptr2]
)
mem[ptr1][ptr2] = maxProfit
return maxProfit
}
dynamicMotivation([2,3,5,1,4]) // 50 is the optimal solution here
50