Prepin
Log in

Identify the subarray within a given array that produces the highest product.

Approach / Explanation

In this task, you are required to create a function that takes an array of integers as input. The objective is to identify the continuous subarray within this array that results in the highest product when all the numbers in that subarray are multiplied together. While this problem may appear straightforward at first, it's important to consider that the array can contain both positive and negative integers. To tackle this issue, we can apply a dynamic programming strategy along with some algorithmic reasoning. A crucial aspect to remember is that a negative number can convert a minimum product into a maximum through multiplication, so it's essential to keep track of both the maximum and minimum products at each index in the array. As you iterate through each element, update the current element's maximum and minimum products if the previous maximum and minimum products are zero. Otherwise, calculate the maximum product by taking the maximum of the current element, the current element multiplied by the previous maximum, and the current element multiplied by the previous minimum. Similarly, compute the minimum product.

Suggested Answer

Here’s a detailed step-by-step method using the array [2, 3, -2, 4]: Start by initializing max_prod, min_prod, and max_result with the first element of the array. Begin iterating through the array from the second element onward. For each element, compute max_prod as the greatest value among the current element, the product of the current element with the previous max_prod, and the product of the current element with min_prod. Similarly, compute min_prod. Update max_result to be the greater of max_prod and max_result. Finally, return the value of max_result. By following this method, you will determine that the maximum subarray product for the given array is 6, achieved from the subarray [2, 3].

Alternative Answer

Consider another example with the array [-1, -3, -10, 0, 60]: Start by setting max_prod, min_prod, and max_result to the first element of the array. Loop through each element in the array beginning from the second element. For each element, determine max_prod as the greatest value among the current element, the product of the current element and the previous max_prod, and the product of the current element and min_prod. Similarly, update min_prod. Update max_result to be the maximum of max_prod and max_result. Finally, return the value of max_result. In this instance, the maximum product of a subarray is 60, which comes from the single-element subarray [60].

Question Details

Difficulty & Category

Medium

Companies

Apple

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.