Leetcode 152: Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
1 public class Solution { 2 public int MaxProduct(int[] nums) { 3 if (nums.Length == 0) return 0; 4 5 int max = nums[0], min = nums[0], result = nums[0]; 6 7 for (int i = 1; i < nums.Length; i++) 8 { 9 int tmax = max, tmin = min; 10 max = Math.Max(nums[i], Math.Max(nums[i] * tmax, nums[i] * tmin)); 11 min = Math.Min(nums[i], Math.Min(nums[i] * tmax, nums[i] * tmin)); 12 13 result = Math.Max(result, max); 14 } 15 16 return result; 17 } 18 }

浙公网安备 33010602011771号