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 maximum product of three numbers of a given array of integers using 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:
Visualize Python code execution:
The following tool visualize what the computer is doing step-by-step as it executes the said program:
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 Python skills with w3resource's quiz
Python: Tips of the Day
Returns a list with n elements removed from the left
Example:
def tips_drop(x, n = 1): return x[n:] print(tips_drop([1, 3, 6])) print(tips_drop([1, 3, 6], 2)) print(tips_drop([1, 3, 3], 45))
Output:
[3, 6] [6] []
- New Content published on w3resource:
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- React - JavaScript Library
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework