È stato utile?

Domanda

Program to find the largest product of two distinct elements in Python

PythonServer Side ProgrammingProgramming

Suppose we have a list of numbers, we have to find the largest product of two distinct elements.

So, if the input is like [5, 3, 7, 4], then the output will be 35

To solve this, we will follow these steps −

  • curr_max := -inf
  • for i in range 0 to size of nums - 1, do
    • for j in range i+1 to size of nums - 1, do
      • if nums[i] * nums[j] > curr_max, then
        • curr_max := nums[i] * nums[j]
  • return curr_max

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      curr_max = float('-inf')
      for i in range(len(nums)):
         for j in range(i+1, len(nums)):
            if nums[i] * nums[j] > curr_max:
               curr_max = nums[i] * nums[j]
      return curr_max
ob = Solution()
print(ob.solve([5, 3, 7, 4]))

Input

[5, 3, 7, 4]

Output

35
raja
Published on 06-Oct-2020 09:57:48
Advertisements
È stato utile?
Non affiliato a Tutorialspoint
scroll top