LeetCode: Maximum Product Subarray

很久没练只能看别人代码了

 1 class Solution {

 2 public:

 3     int maxProduct(int A[], int n) {

 4         if (n == 0) return 0;

 5         int curMax, curMin, ans;

 6         ans = curMax = curMin = A[0];

 7         for (int i = 1; i < n; ++i) {

 8             int tmp = curMin*A[i];

 9             curMin = min(A[i], min(tmp, curMax*A[i]));

10             curMax = max(A[i], max(tmp, curMax*A[i]));

11             ans = max(ans, curMax);

12         }

13         return ans;

14     }

15 };

 C#

 1 public class Solution {

 2     public int MaxProduct(int[] nums) {

 3         if (nums.Length == 0) return 0;

 4         int curMax = nums[0], curMin = nums[0], ans = nums[0];

 5         for (int i = 1; i < nums.Length; i++) {

 6             int tmp = curMin * nums[i];

 7             curMin = Math.Min(nums[i], Math.Min(tmp, curMax * nums[i]));

 8             curMax = Math.Max(nums[i], Math.Max(tmp, curMax * nums[i]));

 9             ans = Math.Max(ans, curMax);

10         }

11         return ans;

12     }

13 }
View Code

 

你可能感兴趣的:(LeetCode)