
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Maximum Product of Two Distinct Elements in Python
Suppose we have a list of numbers called nums, we have to find the largest product of two unique elements.
So, if the input is like nums = [8, -3, 1, -5], then the output will be 15, (-3)*(-5) = 15 which is maximum here.
To solve this, we will follow these steps −
n := size of nums
nums_sort := sort the list nums
max_left := nums_sort[0] * nums_sort[1]
max_right := nums_sort[n-1] * nums_sort[n-2]
ans := maximum of max_left and max_right
return ans
Example
Let us see the following implementation to get better understanding
def solve(nums): nums_sort = sorted(nums) max_left = nums_sort[0] * nums_sort[1] max_right = nums_sort[-1] * nums_sort[-2] ans = max(max_left, max_right) return ans nums = [8, -3, 1, -5] print(solve(nums))
Input
[8, -3, 1, -5]
Output
15
Advertisements