1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public class Solution { public int maxProduct(int[] nums) { int prePos = 1; int preNeg = 1; int max = Integer.MIN_VALUE; int singleMax = Integer.MIN_VALUE; for (int i = 0; i < nums.length; i++){ singleMax = Math.max(nums[i], singleMax); if (nums[i] > 0){ prePos = prePos*nums[i]; preNeg = (preNeg*nums[i] < 0)?preNeg*nums[i]:1; max = Math.max(max, prePos); }else if (nums[i] < 0){ if (preNeg*nums[i] > 0) max = Math.max(max, preNeg*nums[i]); int temp = prePos; prePos = (preNeg*nums[i] > 0)?preNeg*nums[i]:1; preNeg = temp*nums[i]; }else{ prePos = preNeg = 1; } } return Math.max(singleMax, max); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Solution { public: int maxProduct(int A[], int n) { if(n<=0) return 0; int ret, curMax, curMin; ret = curMax = curMin = A[0]; for(int i=1; i<n; i++) { int temp = curMax; curMax = max(max(curMax*A[i], curMin*A[i]),A[i]); curMin = min(min(temp*A[i], curMin*A[i]),A[i]); ret = max(ret, curMax); } return ret; } }; |
No comments:
Post a Comment