Leetcode NO.152 Maximum Product Subarray
2015-05-08 07:09
316 查看
本题题目要求如下:
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array
the contiguous subarray
开始这道题我并没有构建出最好的DP模型,虽然思路大致正确,也解出了结果,而且运行结果不错,但是代码不够简练。。
现在介绍下本题的做法。。。
本题设定两个vector,一个存储以该点为终点的最小值(绝对值最大的负值),另外一个存储以该点为终点的最大值。。
比如本题的例子[2,3,-2,4]
运行结果如下:
初始化:pos[0,0,0,0], neg[0,0,0,0]
对2处理: pos[2,0,0,0], neg[0,0,0,0]
对3处理: pos[2,6,0,0], neg[0,0,0,0] // 2 * 3 = 6
对-2处理: pos[2,6,0,0], neg[0,0,-12,0] // 6 * -2 = -12
对4处理: pos[2,6,0,0], neg[0,0,-12,-24]
公式如下:
pos[i] = max(pos[i-1]*num[i], neg[i-1]*num[i], num[i])
neg[i] = min(pos[i-1]*num[i], neg[i-1]*num[i], num[i])
代码如下:
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.
开始这道题我并没有构建出最好的DP模型,虽然思路大致正确,也解出了结果,而且运行结果不错,但是代码不够简练。。
现在介绍下本题的做法。。。
本题设定两个vector,一个存储以该点为终点的最小值(绝对值最大的负值),另外一个存储以该点为终点的最大值。。
比如本题的例子[2,3,-2,4]
运行结果如下:
初始化:pos[0,0,0,0], neg[0,0,0,0]
对2处理: pos[2,0,0,0], neg[0,0,0,0]
对3处理: pos[2,6,0,0], neg[0,0,0,0] // 2 * 3 = 6
对-2处理: pos[2,6,0,0], neg[0,0,-12,0] // 6 * -2 = -12
对4处理: pos[2,6,0,0], neg[0,0,-12,-24]
公式如下:
pos[i] = max(pos[i-1]*num[i], neg[i-1]*num[i], num[i])
neg[i] = min(pos[i-1]*num[i], neg[i-1]*num[i], num[i])
代码如下:
class Solution { public: int maxProduct(vector<int>& nums) { vector<int> pos(nums.size(), 0); vector<int> neg(nums.size(), 0); if (nums[0] > 0) { pos[0] = nums[0]; } else { neg[0] = nums[0]; } int max_item = nums[0]; for (int i = 1; i < nums.size(); ++i) { pos[i] = max(pos[i-1]*nums[i], max(nums[i], neg[i-1]*nums[i])); neg[i] = min(pos[i-1]*nums[i], min(nums[i], neg[i-1]*nums[i])); if (pos[i] > max_item) max_item = pos[i]; } return max_item; } };
相关文章推荐
- leetCode No.152 Maximum Product Subarray
- LeetCode Maximum Product Subarray 最大子序列积
- LeetCode Maximum Product Subarray
- LeetCode 152: Maximum Product Subarray
- [leetcode]Maximum Product Subarray
- Leetcode131: Maximum Product Subarray
- LeetCode Maximum Product SubArray
- LeetCode之“动态规划”:Maximum Product Subarray
- [Leetcode] Maximum Product Subarray
- 【LeetCode】【Solution】Maximum Product Subarray
- Leetcode 152 Maximum Product Subarray
- LeetCode 53/152 Maximum Subarray/Maximum Product Subarray(动态规划)
- LeetCode: Maximum Product Subarray
- leetcode maximum-product-subarray
- LeetCode-152:Maximum Product Subarray (乘积最大连续子数组) -- medium
- leetcode--Maximum Product Subarray
- Leetcode(152) Maximum Product Subarray
- LeetCode-Maximum Product Subarray-最大乘积子数组-情况判断
- LeetCode题库解答与分析——#152. 乘积最大子序列MaximumProductSubarray
- [leetcode]Maximum Product Subarray