All problems

Problem 958

Maximum Alternating Subsequence Sum

Medium · 20 pts · Array, Dynamic Programming

Problem

The alternating sum of a sequence adds the elements at even positions and subtracts those at odd positions (positions counted from 0 within the sequence), so 4 2 5 3 gives 4 - 2 + 5 - 3 = 4. Choose a non-empty subsequence of the array (keeping the order) with the largest alternating sum. Keep two values while scanning: the best sum of a subsequence whose last chosen element was added, and of one whose last element was subtracted.

Input

The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].

Output

Print the maximum alternating sum.

Constraints

1 <= N <= 100000; 1 <= A[i] <= 10^5

Example input

4
4 2 5 3

Example output

7

Explanation

From 4 2 5 3, choose 4 2 5: the alternating sum is 4 - 2 + 5 = 7, the best possible.

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

Previous: Best Sightseeing Pair Next: Filling Bookcase Shelves