Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created June 8, 2017 19:37

Revisions

  1. jianminchen created this gist Jun 8, 2017.
    49 changes: 49 additions & 0 deletions Leetcode121_buyAndSellStock.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,49 @@
    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;
    }
    }
    }