Skip to content

Instantly share code, notes, and snippets.

@alldroll
Created February 27, 2020 17:18
Show Gist options
  • Select an option

  • Save alldroll/c52a1261f562e9166dbb14c5f36db697 to your computer and use it in GitHub Desktop.

Select an option

Save alldroll/c52a1261f562e9166dbb14c5f36db697 to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/maximum-product-subarray
func maxProduct(nums []int) int {
numsLen := len(nums)
if numsLen == 0 {
return 0
}
if numsLen == 1 {
return nums[0]
}
memorized := make([][2]int, numsLen)
memorized[0] = [2]int{nums[0], nums[0]}
result := nums[0]
for i := 1; i < numsLen; i++ {
memorized[i][0] = max(max(memorized[i - 1][0] * nums[i], nums[i]), memorized[i-1][1] * nums[i])
memorized[i][1] = min(min(memorized[i - 1][1] * nums[i], nums[i]), memorized[i-1][0] * nums[i])
result = max(result, memorized[i][0])
}
return result
}
func max(a, b int) int {
if a < b {
return b
}
return a
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment