mediumArraysPattern: basic-concepts
Maximum Subarray Product Solution
Problem Statement
You are given an array of integers `values` representing commodity multipliers. Write a function to find the maximum product of a subarray within the given array, where the subarray must contain at least one element.
Examples
Example 1:
Input:{"values":[23,-24]}
Output:6
Explanation: The maximum product of a subarray is calculated by considering all possible subarrays. For this input, the subarray [2,3] has a product of 6, which is the maximum.
Example 2:
Input:{"values":[-20,-1]}
Output:0
Explanation: The presence of 0 in the array makes any subarray that includes it have a product of 0, which is the maximum product in this case since all other subarrays have negative products.
Constraints
- The input array will have at least one element.
- The input array will contain only integers between -100 and 100.
Time: O(n) Space: O(1)
The optimal approach uses dynamic programming to keep track of the maximum and minimum product of subarrays ending at each position, allowing it to handle negative numbers and find the maximum product in linear time.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
