标签:actually sam [] class product ret java prefix tco
Use prefix product(sum? actually much the same).
class Solution {
public int maxProduct(int[] nums) {
int maxNeg = 1, minPos = 1;
int product = 1;
int ret = Integer.MIN_VALUE;
for (int val: nums) {
product *= val;
if (product == 0) {
ret = Math.max(ret, val);
product = maxNeg = minPos = 1;
}
else if (product > 0) {
ret = Math.max(ret, product / minPos);
minPos = Math.min(minPos, product);
}
else {
ret = Math.max(ret, product / maxNeg);
maxNeg = maxNeg > 0? product: Math.max(maxNeg, product);
}
}
return ret == Integer.MIN_VALUE? 0: ret;
}
}
leetcode 152. Maximum Product Subarray
标签:actually sam [] class product ret java prefix tco
原文地址:https://www.cnblogs.com/exhausttolive/p/10618328.html