Maximum Product Subarray
Updated
Problem statement
Given a nonempty integer array nums, return the largest product obtainable by multiplying every element in one nonempty contiguous subarray.
A contiguous subarray uses consecutive elements of nums. You may choose a single element, and the array may contain negative numbers and zeros.
Return the product value, rather than the chosen subarray or its indices. Products are exact signed integers; do not apply a modulus.
Function
maxProduct(nums: int[]) → longExamples
Example 1
nums = [2,3,-2,4]return = 6The subarray [2,3] has product 6. Any subarray containing -2 has a negative product, and the remaining singleton [4] has product 4.
Example 2
nums = [-2,3,-4]return = 24The entire array is contiguous, and its product is (-2) * 3 * (-4) = 24. The two negative factors produce a positive product.
Example 3
nums = [-2,0,-1]return = 0The singleton [0] has product 0, larger than either negative singleton. The values -2 and -1 cannot be multiplied together without including the intervening zero.
Constraints
1 <= nums.length <= 10^5.-10 <= nums[i] <= 10.- The product of every nonempty contiguous subarray is guaranteed to lie between
-10^18and10^18, inclusive. - The returned value must use a signed
64-bitinteger or a wider exact integer type.
More Hartford Financial Services interview questions
Similar questions at other companies
- Maximal SquareAmazon · ONSITE INTERVIEW
- Distinct Subset SumsGoogle · ONSITE INTERVIEWGoogle interview questions
- Count Subsets With a Target SumSafe Security · ONSITE INTERVIEW
- Maximum Subarray Sum with One DeletionOracle · ONSITE INTERVIEWOracle interview questions
- Best Time to Buy and Sell Stock IIKotak Mahindra Bank · ONSITE INTERVIEWKotak Mahindra Bank interview questions
- Coin ChangeMicrosoft · ONSITE INTERVIEWMicrosoft interview questions
- Maximum SubarrayUpstart · ONSITE INTERVIEWUpstart interview questions
- Smallest Sufficient TeamExpedia · ONSITE INTERVIEWExpedia interview questions
- Word BreakMoveworks · ONSITE INTERVIEWMoveworks interview questions
- Maximum Value from Circular HousesDigitalOcean · ONSITE INTERVIEWDigitalOcean interview questions