w3resource

Python: Compute maximum product of three numbers of a given array of integers using Heap queue algorithm

Python heap queue algorithm: Exercise-8 with Solution

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:

Python heap queue algorithm: Compute maximum product of three numbers of a given array of integers using Heap queue algorithm.

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/heap-queue-algorithm/python-heapq-exercise-8.php