C# solution: local&global


  • 0
    B
    public class Solution 
    {
        public int MaxProfit(int[] prices) 
        {
            if (prices.Length == 0) return 0;
    
            var global = 0;
    
            var localMin = prices[0];
            
            for(int i = 1; i < prices.Length; i++)
            {
                var local = prices[i] - localMin;
                if (local > 0)
                {
                    global += prices[i] - localMin;
                    localMin = prices[i];               
                }
                else
                {
                    localMin = Math.Min(localMin, prices[i]);
                }
    
            }
    
            return global;
        }
    }
    

Log in to reply
 

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