首页 > 其他 > 详细

152. Maximum Product Subarray (Array; DP)

时间:2016-12-12 01:34:54      阅读:134      评论: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.

思路:类似Maximum Subarray,不同的是

  • max(max_local*nums[i], nums[i])表示:如果之前的数max_local和nums[i]符号相反,那么nums[i]会是max
  • max(max(max_local*nums[i], nums[i]), min_local*nums[i])表示:如果nums[i]是个负数,那么就可能和min_local组成局部最优=>这是为什么我们要设置min_local
class Solution {
public:
    int maxProduct(vector<int>& nums) {
         int max_local = nums[0];
         int min_local = nums[0];
         int max_copy;
         int global = nums[0];
         
         for(int i = 1; i < nums.size(); i++){
              max_copy = max_local;
              max_local = max(max(max_local*nums[i], nums[i]), min_local*nums[i]);
              min_local = min(min(max_copy*nums[i], nums[i]), min_local*nums[i]);
              global = max(global,max_local);
         }
         
         return global;
    }
};

 

152. Maximum Product Subarray (Array; DP)

原文:http://www.cnblogs.com/qionglouyuyu/p/6161000.html

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