/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
	public static void main (String[] args) throws java.lang.Exception
	{
		/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
	public static void main (String[] args) throws java.lang.Exception
	{
		// Test Input here
		int[] inputArr = new int[] {38, 40, 42, 35, 23, 50};
		
		int size = inputArr.length;
		int[][] maxValuesFrom = new int[6][6];
		
		for( int start=0; start < size-1; start++)
		{
			int minimumStartingPrice = inputArr[start];
			int maximumEndingPrice = inputArr[start];
			
			for( int end=start+1; end < size; end++)
			{
				if( maximumEndingPrice < inputArr[end] )
				{
					maximumEndingPrice = inputArr[end];	
				}
				
				maxValuesFrom[start][end] = ( maximumEndingPrice - minimumStartingPrice );
			}
		}
		
		int finalMaxStockPrice=0;
		for( int startIndex=0; startIndex < size; startIndex++)
		{
			int localMax=maxValuesFrom[startIndex][size-1];
			for(int endIndex=startIndex+1; endIndex < size; endIndex++)
			{
				int sumValue = maxValuesFrom[startIndex][endIndex] + maxValuesFrom[endIndex+1][size-1];
				
				if( sumValue > maxValuesFrom[startIndex][size-1] && sumValue > localMax )
				{
					localMax = sumValue;
				}
			}
			
			if( finalMaxStockPrice < localMax )
			{
				finalMaxStockPrice = localMax;
			}
		}
	}
}
