Table of Contents
Maximum Product Subarray
Problem Statement
Given an integer array nums
, find a subarray that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1:
Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6.
Example 2:
Input: nums = [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
Constraints:
1 <= nums.length <= 2 * 104
-10 <= nums[i] <= 10
- The product of any subarray of
nums
is guaranteed to fit in a 32-bit integer.
Logic / Trick
- Use Kadane’s algorithm variation for products.
- Maintain 2 products
- MaxProduct
- MinProduct (In case of two negative numbers)
Golang Solution
func maxProduct(nums []int) int {
maxProdSoFar := nums[0]
minProdSoFar := nums[0]
result := nums[0]
startIndex := 0
endIndex := 0
currentStart := 0
for i := 1; i < len(nums); i++ {
// case-1 : 0
// reset running product in case of occurrence of 0 value
// Also check if result is negative or not
// if result is -ve, then reset it to 0
// skip remaining calculation for 0 value occurence
if nums[i] == 0 {
minProdSoFar, maxProdSoFar = 0, 0
currentStart = i + 1
if result < 0 {
result = 0
startIndex = i
endIndex = i
}
continue
}
// case-2 : -ve number
// Swapping in the beginning is important
// This will help us to get to correct result in case of
// negative number occurence
if nums[i] < 0 {
minProdSoFar, maxProdSoFar = maxProdSoFar, minProdSoFar
}
// Track MaxProduct
// Similar to kadane’ compare running product sum with new number and
// update according maxProdSoFar
if (maxProdSoFar * nums[i]) < nums[i] {
maxProdSoFar = nums[i]
} else {
maxProdSoFar = maxProdSoFar * nums[i]
}
// Track MinProduct
// Similar to kadane’ compare running product sum with new number and
// update according minProdSoFar
if nums[i] < (minProdSoFar * nums[i]) {
minProdSoFar = nums[i]
} else {
minProdSoFar = minProdSoFar * nums[i]
}
// Update Final result
// update the maxProdSum in result if it is bigger than the previously saved
if result < maxProdSoFar {
result = maxProdSoFar
startIndex = currentStart
endIndex = i
}
fmt.Printf("Max product subarray is from index %d to %d\n", startIndex, endIndex)
}
return result
}
Visit https: https://codeandalgo.com for more such contents
Leave a Reply