码迷,mamicode.com
首页 > 其他好文 > 详细

Maximum Product Subarray

时间:2015-07-13 22:22:20      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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.

 

代码:

 1 public class Solution {
 2     public int maxProduct(int[] nums) 
 3     {
 4         int max=nums[0];
 5         int min=nums[0];
 6         int maxAns=nums[0];
 7         
 8         for(int i=1;i<nums.length;i++)
 9         {
10             int mx=max;
11             int mn=min;
12             max=Math.max(Math.max(nums[i],mx*nums[i]),mn*nums[i]);
13             min=Math.min(Math.min(nums[i],mx*nums[i]),mn*nums[i]);
14             maxAns=Math.max(max,maxAns);    
15         }
16         
17         return maxAns;
18     }
19 }

注意红色部分,变量maxAns的存在很重要。

Maximum Product Subarray

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4643977.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!