Note: study again. Time: O(n), Space: O(1)
(nums []int)
| 5 | // Note: study again. |
| 6 | // Time: O(n), Space: O(1) |
| 7 | func maxProduct(nums []int) int { |
| 8 | minCurrent := nums[0] |
| 9 | maxCurrent := nums[0] |
| 10 | max := nums[0] |
| 11 | |
| 12 | for i := 1; i < len(nums); i++ { |
| 13 | // if the next number is negative, then swap minCurrent and maxCurrent |
| 14 | // so that we can maximize the swapping signs of our most minimum number |
| 15 | if nums[i] < 0 { |
| 16 | minCurrent, maxCurrent = maxCurrent, minCurrent |
| 17 | } |
| 18 | |
| 19 | // similar to Kadane's algorithm, with small twist for negative number products |
| 20 | minCurrent = int(math.Min(float64(nums[i]), float64(minCurrent*nums[i]))) |
| 21 | maxCurrent = int(math.Max(float64(nums[i]), float64(maxCurrent*nums[i]))) |
| 22 | max = int(math.Max(float64(max), float64(maxCurrent))) |
| 23 | } |
| 24 | |
| 25 | return max |
| 26 | } |
| 27 | |
| 28 | // First, O(n^2) solution. |
| 29 | func maxProduct0(nums []int) int { |
no outgoing calls