Python: Compute maximum product of three numbers of a given array of integers using Heap queue algorithm
8. Maximum Product of Three Numbers
Write a Python program to compute the maximum product of three numbers in a given array of integers using the heap queue algorithm.
Sample Solution:
Python Code:
def maximumProduct(nums):
import heapq
a, b = heapq.nlargest(3, nums), heapq.nsmallest(2, nums)
return max(a[0] * a[1] * a[2], a[0] * b[0] * b[1])
arr_nums = [12, 74, 9, 50, 61, 41]
print("Original array elements:")
print(arr_nums)
print("Maximum product of three numbers of the said array:")
print(maximumProduct(arr_nums))
Sample Output:
Original array elements: [12, 74, 9, 50, 61, 41] Maximum product of three numbers of the said array: 225700
Flowchart:

For more Practice: Solve these Related Problems:
- Write a Python program to compute the maximum product of three numbers in a list using heapq.nlargest for the top three and heapq.nsmallest for the two smallest.
- Write a Python function to find the maximum product of any three integers by evaluating candidates from both ends of the sorted list using heapq.
- Write a Python script to calculate the maximum product of three numbers in a list using a heap-based approach and then verify the result using brute-force.
- Write a Python program to determine the maximum product of three numbers from an array, considering both positive and negative values, using heapq.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to find the kth largest element in an unsorted array using Heap queue algorithm.
Next: Write a Python program to find the top k integers that occur the most frequently from a given lists of sorted and distinct integers using Heap queue algorithm.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.