首页 > 代码库 > 152. Maximum Product Subarray (Array; DP)
152. Maximum Product Subarray (Array; DP)
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)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。