C# - buy low, sell high


  • 0

    The other solutions where you buy and sell on same day are simpler and better all around, but this ones a little different so just thought I'd share!

    public int MaxProfit(int[] prices) {
        int profit = 0;
        int i = 0;
        while (i < prices.Length)
        {
            // buy at valley
            while (i < prices.Length - 1 && prices[i+1] <= prices[i])
            {
                i++;
            }
            int valley = i < prices.Length ? prices[i] : int.MaxValue;
            i++;
            
            // sell at peak
            while (i < prices.Length - 1 && prices[i+1] >= prices[i])
            {
                i++;
            }
            int peak = i < prices.Length ? prices[i] : int.MinValue;
            
            if (peak > valley) profit += peak - valley;
            i++;
        }
        return profit;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.