funcmaxProduct(nums []int) int {// min := nums[0] res := nums[0] dp1 := []int{nums[0]} dp2 := []int{nums[0]}for i:=1; i<len(nums); i++ { dp1 =append(dp1, max(nums[i], dp1[i -1] * nums[i], dp2[i -1]* nums[i])) dp2 =append(dp2, min(nums[i], dp2[i -1] * nums[i], dp1[i -1]* nums[i]))if dp1[i] > res { res = dp1[i] } }return res}funcmax(a, b, c int) int {if a >= b && a >= c {return a } elseif b >= a && b >= c{return b } return c}funcmin(a, b, c int) int {if a <= b && a <= c {return a } elseif b <= a && b <= c{return b } return c}
精簡版,把兩個陣列變成兩個變數
Runtime: 4 ms, faster than 93.98%
Memory Usage: 3.3 MB, less than 100%
funcmaxProduct(nums []int) int { res := nums[0] maxx := nums[0] minn := nums[0]for i:=1; i<len(nums); i++ { premax := maxx maxx =max(nums[i], maxx * nums[i], minn* nums[i]) minn =min(nums[i], minn * nums[i], premax* nums[i])if maxx > res { res = maxx } }return res}funcmax(a, b, c int) int {if a >= b && a >= c {return a } elseif b >= a && b >= c{return b } return c}funcmin(a, b, c int) int {if a <= b && a <= c {return a } elseif b <= a && b <= c{return b } return c}