0

I would like to take a long input and print the maximum pairwise product between them but i'm getting 0 as my output. e.g. would like to take 10^5 and 9^4 as my input and print maximum pairwise product 9^9 but i'm getting 0 as my answer. So how to solve this problem of taking long input in python3?

   n = len(numbers)
   largest = 0
   second = 0
   for i in range(0,n):
     if numbers[i] > largest:
       second = largest
       largest = numbers[i]
       
   max_product = largest * second
   return max_product

if __name__ == '__main__':
   input_numbers = []
   input_n = int(input())
   input_numbers = [int(x) for x in input().split()]
   print(max_pairwise_product(input_numbers))
Cem
  • 93
  • 1
  • 1
  • 13

1 Answers1

0

Your code has some syntax erros in the main function about input, this should fix:

if __name__ == '__main__':
   input_numbers = []
   input_n = input()
   input_numbers = [int(x) for x in input_n.split()]
   print(max_pairwise_product(input_numbers))

About the logic, think about what will occurs if your is 3 2 1 0. Since the max value will be replace in the first iteration, second will receive the current value of largest that is 0 and this will never be replaced with another one. To fix that you should first check if the value is bigger than the second one and only after that check if it bigger than largest. The following snippet should solve your problem:

def max_pairwise_product(numbers):
  n = len(numbers)
  largest = float('-inf')
  second = float('-inf')
  for i in range(0, n):
    if numbers[i] > second:
      if numbers[i] > largest:
        second = largest
        largest = numbers[i]
      else:
        second = numbers[i]
  
  max_product = largest * second
  return max_product

I also changed the values of largest and second to start if negative infinity.

j3r3mias
  • 365
  • 2
  • 12