Java for LeetCode 152 Maximum Product Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

解题思路:

计算连续的积最大,由于会有负数出现,因此需要用两个int表示包含nums[i]的最大值和最小值,然后res=Math.max(res, max)即可,JAVA实现如下:

    public int maxProduct(int[] nums) {
if(nums.length==1)
return nums[0];
int max=nums[0],min=nums[0],res=nums[0],maxTemp=0,mintemp=0;
for(int i=1;i<nums.length;i++){
maxTemp=max*nums[i];
mintemp=min*nums[i];
max=Math.max(nums[i],Math.max(maxTemp, mintemp));
min=Math.min(nums[i],Math.min(maxTemp, mintemp));
res=Math.max(res, max);
}
return res;
}
上一篇:XyTalk企业即时通讯IM开始开源


下一篇:React native 之设置IOS的图标,名称和启动图(下篇文章会讲到RN的android的相关设置)