Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
A:
----------------------自己的代码-------略---------------
就是先 用0 把所有的A[i]分开, 然后,只算有正负的。这样,每次相乘的结果,绝对值都变大了。因此,可以直接maxPosProduct 和minNegProduct互相转换。
但其实,这样是没有必要的-----------------
------------------------参考了别人的geeksforgeeks的代码--------------------
public class Solution {
public int maxProduct(int[] A) {
assert(A!=null && A.length >0);
if(A.length == 1)
return A[0];
int result = Integer.MIN_VALUE, maxEndHere = 1;// max positive product ending at the current position
int minEndHere = 1;// min negative product ending at the current position
for (int i = 0; i < A.length; i++) {
if (A[i] > 0) {
maxEndHere = maxEndHere * A[i];
minEndHere = Math.min(minEndHere * A[i],1);
result = Math.max(result,maxEndHere);
} else if(A[i]==0) {
maxEndHere = 1;
minEndHere = 1;
result = Math.max(result,0);// 0 can also be a product result
}else{ // A[i]<0
result = Math.max(minEndHere*A[i],result);
int tmp = maxEndHere;
maxEndHere = Math.max( minEndHere*A[i],1);
minEndHere = tmp*A[i];
}
}
return result;
}
}
Mistakes: 1: 就是上面的这个思路了。 每次用maxEndHere 等,每次初始值都设为1
2: when A[i]< 0 , we need calculate the result at the beginning, 因此, 我们不能简单地把result = Math.max( ) 放到if 条件的外面。
3: 切记: A.length ==1的时候要单独列出来。
Learned: ----------
1: java中, given
int a =3;
int A = {1,2,3};
运行语句: A[a/2]是正确的
2:函数要求的返回值是double, 我们可以return一个int类型。语法是正确的
3
No comments:
Post a Comment