首页 > 编程语言 > 详细

152. Maximum Product Subarray java solutions

时间:2016-07-03 21:12:52      阅读:139      评论: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         if(nums == null || nums.length < 1) return 0;
 4         int ans = nums[0];
 5         int max = nums[0], min = nums[0];
 6         for(int i = 1; i < nums.length; i++){
 7             int tmp1 = max*nums[i];
 8             int tmp2 = min*nums[i];
 9             max = Math.max(nums[i],Math.max(tmp1,tmp2));
10             min = Math.min(nums[i],Math.min(tmp1,tmp2));
11             ans = Math.max(max,ans);
12         }
13         return ans;
14     }
15 }

 

152. Maximum Product Subarray java solutions

原文:http://www.cnblogs.com/guoguolan/p/5638546.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!