MCPcopy Create free account
hub / github.com/austingebauer/go-leetcode / maxProduct

Function maxProduct

maximum_product_subarray_152/solution.go:7–26  ·  view source on GitHub ↗

Note: study again. Time: O(n), Space: O(1)

(nums []int)

Source from the content-addressed store, hash-verified

5// Note: study again.
6// Time: O(n), Space: O(1)
7func 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.
29func maxProduct0(nums []int) int {

Callers 1

Test_maxProductFunction · 0.85

Calls

no outgoing calls

Tested by 1

Test_maxProductFunction · 0.68