prices = readlines.map(&:to_i)[1..-1]

profits = prices[0...-1].map.with_index { |price, index|
  profit = prices[index + 1] - price
  [profit, index]
}

positive_profits, negative_profits = profits.partition { |(profit, _)|
  profit >= 0
}

if positive_profits.empty?
  puts negative_profits.max_by { |(profit, _)| profit }.first
  exit
end

profit_sum = nil
max_profit = 0
positive_profits[0...-1].each_with_index do |(profit, index), i|
  next_index = positive_profits[i + 1][1]
  profit_sum ||= profit

  profit_sum += positive_profits[i + 1][0] if (next_index - index) == 1
  max_profit = [profit_sum, max_profit].max
  profit_sum = nil unless (next_index - index) == 1
end

puts max_profit