OneCompiler

Best time to buy and sell stock

158
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace OneCompiler
{
	public class Program
	{
		public static void Main(string[] args)
		{
			int n = int.Parse(Console.ReadLine());
			
			int[] arr = Array.ConvertAll(Console.ReadLine().Split(" "), new Converter<string,int>(StringToInteger));
			
			var maxProfit = MaxProfit(arr);
			
			Console.Write(maxProfit);
		}
		
		private static int StringToInteger(string s)
		{
		  return int.Parse(s);
		}
		
		private static int MaxProfit(int[] arr)
		{
		  int n = arr.Length;
		  
		  var buy = arr[0];
		  
		  var maxProfit = 0;
		  
		  for (int i = 1; i < n; i++)
		  {
		    if (buy > arr[i])
		    {
		      buy = arr[i];
		    }
		    else
		    {
		      var profit = arr[i] - buy;
		      maxProfit = Math.Max(maxProfit, profit);
		    }
		  }
		  
		  return maxProfit;
		}
	}
}