Created
June 8, 2017 19:37
-
-
Save jianminchen/d608f91178433495d185a99e480dcbe2 to your computer and use it in GitHub Desktop.
Leetcode 121 - easy level, buy and sell the stock
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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