Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created June 8, 2017 19:37
Show Gist options
  • Save jianminchen/d608f91178433495d185a99e480dcbe2 to your computer and use it in GitHub Desktop.
Save jianminchen/d608f91178433495d185a99e480dcbe2 to your computer and use it in GitHub Desktop.
Leetcode 121 - easy level, buy and sell the stock
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Leetcode121_BesttimeBuyAndSellStock
{
class Program
{
static void Main(string[] args)
{
}
public int MaxProfit(int[] prices)
{
if (prices == null || prices.Length == 0)
{
return 0;
}
int minimumPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.Length; i++)
{
var current = prices[i];
bool currentIsBigger = current > minimumPrice;
bool currentIsMinimum = current < minimumPrice;
if (currentIsBigger)
{
var currentProfit = current - minimumPrice;
bool currentIsMax = currentProfit > maxProfit;
maxProfit = currentIsMax ? currentProfit : maxProfit;
}
if (currentIsMinimum)
{
minimumPrice = prices[i];
}
}
return maxProfit;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment