#K90557. Max Non-Adjacent Product

    ID: 37778 Type: Default 1000ms 256MiB

Max Non-Adjacent Product

Max Non-Adjacent Product

You are given an array of integers. Your task is to compute the maximum product obtained by selecting two non-adjacent elements from the array.

Two elements are considered non-adjacent if the difference between their indices is at least 2. Specifically:

  • If the array contains only one element, output that element.
  • If the array contains exactly two elements, output the maximum of the two.
  • If the array contains three or more elements, choose two elements that are not next to each other and maximize their product.

Note that the array may contain negative numbers and zeros, so take care when computing the maximum product.

In mathematical form, if the array is represented as \(a_0, a_1, \ldots, a_{n-1}\), you are to find:

\(\max_{0 \leq i < j \leq n-1,\; j-i \ge 2}(a_i\times a_j)\)

inputFormat

The input is read from standard input (stdin) and has the following format:

n
a1 a2 a3 ... an

Where n (1 ≤ n ≤ 105 or similar) is the number of elements in the array and the next line contains n integers separated by spaces.

outputFormat

Output a single integer to standard output (stdout) which is the maximum product obtained from any pair of non-adjacent elements (or according to the special rules when n is 1 or 2).

## sample
5
3 4 5 1 2
15