Prepin
Log in

Identify the highest product of two integers within an array.

Approach / Explanation

This question requires you to determine the highest product obtainable by multiplying two numbers from a given array. You have an array consisting of both positive and negative integers, and your goal is to identify the two numbers that yield the greatest product when multiplied together. Key considerations include: If the array consists solely of positive numbers or only negative numbers, the maximum product will come from multiplying the two largest numbers. If the array includes both positive and negative numbers, the maximum product can be found by either multiplying the two largest positive numbers or the two smallest negative numbers (since the product of two negative numbers results in a positive). The anticipated time complexity for solving this problem is O(n log n) if you sort the array, or O(n) if you directly find the maximum and minimum elements.

Suggested Answer

A practical method to address this issue is by sorting the array in non-decreasing order. Once sorted, the highest product can be determined by multiplying either the two largest numbers (found at the end of the sorted array) or the two smallest numbers (located at the beginning of the sorted array). Below is an example of Python code illustrating this method: def maximum_product ( arr ) : arr . sort ( ) return max ( arr [ 0 ] * arr [ 1 ] , arr [ - 1 ] * arr [ - 2 ] ) This approach is effective because in Python, arr[0] retrieves the smallest element, arr[1] retrieves the second smallest element, arr[-2] retrieves the second largest element, and arr[-1] retrieves the largest element in the array.

Alternative Answer

Another effective technique is to identify the two largest and two smallest numbers in the array without sorting it. This method achieves a time complexity of O(n), which is an enhancement over the previous approach. Below is an example of Python code: def maximum_product ( arr ) : a = b = float ( '-inf' ) # two largest elements c = d = float ( 'inf' ) # two smallest elements for num in arr : if num > a : # find the largest number a , b = num , a elif num > b : # find the second largest number b = num if num < c : # find the smallest number c , d = num , c elif num < d : # find the second smallest number d = num return max ( a * b , c * d ) This solution involves a single traversal of the array to determine the two largest and two smallest numbers. The maximum product is calculated as the greater value between the product of the two largest numbers and the product of the two smallest numbers.

Question Details

Difficulty & Category

Medium
algorithms

Companies

Amazon

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

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