Problem:
Score : 300 points

Problem Statement

There is an integer sequence A of length N whose values are unknown.

Given is an integer sequence B of length N-1 which is known to satisfy the following:

B_i \geq \max(A_i, A_{i+1})

Find the maximum possible sum of the elements of A.

Constraints

All values in input are integers.

2 \leq N \leq 100

0 \leq B_i \leq 10^5

Input

Input is given from Standard Input in the following format:

N
B_1 B_2 ... B_{N-1}

Output

Print the maximum possible sum of the elements of A.

Sample Input 1

3
2 5

Sample Output 1

9

A can be, for example, ( 2 , 1 , 5 ), ( -1 , -2 , -3 ), or ( 2 , 2 , 5 ). Among those candidates, A = ( 2 , 2 , 5 ) has the maximum possible sum.

Sample Input 2

2
3

Sample Output 2

6

Sample Input 3

6
0 153 10 10 23

Sample Output 3

53

Solution in Java8 (OpenJDK 1.8.0) (judge verdict: Accepted)


import java.util.ArrayList;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scn=new Scanner(System.in);
		int n=scn.nextInt();
		TreeMap<Integer,ArrayList<Integer>> tmap=new TreeMap<>();
		for(int i=0;i<n-1;i++) {
			int x=scn.nextInt();
			if(tmap.containsKey(x)) {
				ArrayList<Integer> a=tmap.get(x);
				a.add(i);
				tmap.put(x, a);
			}else{
				ArrayList<Integer> a=new ArrayList<>();
				a.add(i);
				tmap.put(x, a);
			}
		}
		int []arr=new int[n];
		for(int i=0;i<n;i++) {
			arr[i]=-1;
		}
		Set<Integer> set=tmap.keySet();
		for(int x:set) {
			ArrayList<Integer> al=tmap.get(x);
			for(int i=0;i<al.size();i++) {
				if(arr[al.get(i)]==-1)
				arr[al.get(i)]=x;
				if(arr[al.get(i)+1]==-1)
				arr[al.get(i)+1]=x;
			}
		}
		int sum=0;
		//System.out.println(tmap);
		for(int i=0;i<n;i++) {
			sum+=arr[i];
		}
		System.out.println(sum);
	}

}