C# solution: local & global, be careful of "+", "-" or "0"


  • 0
    B
    public class Solution 
    {
        public int MaxProduct(int[] nums) 
        {
            if (nums.Length == 0) return 0;
    
            var globalMax = nums[0];
            
            var preMin = nums[0];
            var preMax = nums[0];
    
            for (int i = 1; i < nums.Length; i++)
            {
                var curMin = 0;
                var curMax = 0;
    
                if (nums[i] == 0)
                {
                    curMin = 0;
                    curMax = 0;
                }
                else if (nums[i] < 0)
                {
                    curMin = Math.Min(nums[i], nums[i] * preMax);
                    curMax = Math.Max(nums[i], nums[i] * preMin);
                }
                else if (nums[i] > 0)
                {
                    curMin = Math.Min(nums[i], nums[i] * preMin);
                    curMax = Math.Max(nums[i], nums[i] * preMax);
                }
    
                preMin = curMin;
                preMax = curMax;
    
                globalMax = Math.Max(preMax, globalMax);
            }
    
            return globalMax;
        }
    }
    

Log in to reply
 

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