[UCSD白板题] Maximum Pairwise Product

时间:2023-11-15 21:53:32

Problem Description

Task.Given a sequence of non-negative integers \(a_0, ..., a_{n-1}\),find the maximum pairwise product,that is,the largest integer that can be obtained by multiplying two different elements from the sequence(or,more formally,\(\max \limits_{0\leq{i \neq j}\leq {n-1}}\ a_ia_j\)).Different elements here mean \(a_i\) and \(a_j\) with \(i \neq j\) (it can be the case that \(a_i=a_j\)).

Input format.The first line of the input contains an integer \(n\).The next line contains\(n\)non-negative integers \(a_0, ..., a_{n-1}\) (separated by spaces).

Constraints.\(2 \leq n \leq 2 \cdot 10^5; 0 \leq a_0, ..., a_{n-1} \leq 10^5\).

Output format.Output a single number - the maximum pairwise product.

Sample 1.
Input:

3
1 2 3

Output:

6

Sample 2.
Input:

10
7 5 14 2 8 8 10 1 2 3

Output:

140

Sample 3.
Input:

5
4 6 2 6 1

Output:

36

Solution

# Uses python3
n = int(input())
a = [int(x) for x in input().split()]
assert(len(a) == n)

fstMax = sndMax = 0
for idx in range(0, n):
    if fstMax < a[idx]:
        fstMax, sndMax = a[idx], fstMax
    elif sndMax < a[idx]:
        sndMax=a[idx]
print(fstMax*sndMax)