Similar to maximum sum subarray, but need a gmin to record the global minimum to handle negative number multiplication.
1 class Solution { 2 public: 3 int maxProduct(int A[], int n) { 4 int result = A[0], gMax = A[0], gMin = A[0]; 5 for (int i = 1; i < n; i++) { 6 int tmp = gMax; 7 gMax = max(max(gMax*A[i], gMin*A[i]), A[i]); 8 gMin = min(min(tmp*A[i], gMin*A[i]), A[i]); 9 result = max(gMax, result); 10 } 11 return result; 12 } 13 };
时间: 2024-10-20 03:32:20