All problems

Problem 385

Maximum Twin Sum of a Linked List

Medium · 20 pts · Linked List, Two Pointers, Stack

Problem

A linked list has an even number of nodes N. The twin of the node at position i (counting from 0) is the node at position N - 1 - i, so the first node pairs with the last, the second with the second-to-last, and so on. The twin sum is the sum of a node's value and its twin's value. Print the largest twin sum in the list. One approach reverses the second half of the list and walks both halves together.

Input

The first line contains N, the number of nodes. The second line contains the N node values from head to tail. N is even.

Output

Print the maximum twin sum.

Constraints

2 <= N <= 100000; N is even; 1 <= value <= 100000

Example input

4
5 4 2 1

Example output

6

Explanation

In 5 4 2 1 the twin pairs are (5, 1) and (4, 2), both summing to 6, so the maximum twin sum is 6.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Swap Kth Nodes from Both Ends Next: Split Linked List into Parts