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]
- if nums[i] * nums[j] > curr_max, then
- for j in range i+1 to size of nums - 1, do
- return curr_max
Let us see the following implementation to get better understanding −
Example
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