FastPrepMaximum Product Subarray

Maximum Product Subarray

Hartford Financial Services logoHartford Financial Services● MediumFULLTIMEONSITE INTERVIEW
Learn

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[]) → long

Examples

Example 1

nums = [2,3,-2,4]return = 6

The 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 = 24

The 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 = 0

The 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^18 and 10^18, inclusive.
  • The returned value must use a signed 64-bit integer or a wider exact integer type.

More Hartford Financial Services problems

See Hartford Financial Services hiring insights
public long maxProduct(int[] nums) {
    // write your code here
}
nums[2,3,-2,4]
expected6
Checking account…