Program to find maximum product of two distinct elements from an array 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

Updated on: 12-Oct-2021

720 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements