[LeetCode] Maximum Product Subarray
来源:互联网 发布:专业设计软件 编辑:程序博客网 时间:2024/05/15 02:29
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
.
- 常规思路
class Solution {public: int maxProduct(int A[], int n) { int product = INT_MIN; for (int i = 0; i < n; i++) { int sub = 1; for (int j = i; j < n; j++) { sub *= A[j]; if (sub > product) { product = sub; } } } return product; }};
上述算法时间复杂度过高,LeetCode返回Time Limit Exceeded
错误提示。
- 动态规划思路
由于数组中有负数存在,一个负数乘以一个负数可能得到一个极大的正数,因此需要维护两个局部变量max_local
和min_local
。转移方程式如下:temp = max_local;
max_local[i] = max(max(max_local * A[i], min_local * A[i]), A[i]);
min_local[i] = min(min(temp * A[i], min_local * A[i]), A[i]);
- 实现代码
/************************************************************* * @Author : 楚兴 * @Date : 2015/2/8 21:43 * @Status : Accepted * @Runtime : 13 ms*************************************************************/class Solution {public: int maxProduct(int A[], int n) { if (n == 0) { return 0; } int max_local = A[0]; int min_local = A[0]; int global = A[0]; for (int i = 1; i < n; i++) { int temp = max_local; max_local = max(max(max_local * A[i], min_local * A[i]), A[i]); min_local = min(min(temp * A[i], min_local * A[i]), A[i]); global = max(global, max_local); } return global; }};
0 0
- Maximum Product Subarray 【LeetCode】
- [LeetCode] Maximum Product Subarray
- leetcode-Maximum Product Subarray
- Maximum Product Subarray -- LeetCode
- LeetCode-Maximum Product Subarray
- [LeetCode]Maximum Product Subarray
- [LeetCode]Maximum Product Subarray
- 【LeetCode】Maximum Product Subarray
- leetcode:Maximum Product Subarray
- leetcode: Maximum Product Subarray
- Leetcode: Maximum Product Subarray
- [LeetCode]Maximum Product Subarray
- Leetcode Maximum Product Subarray
- [Leetcode]Maximum Product Subarray
- Leetcode--Maximum Product Subarray
- Maximum Product Subarray [leetcode]
- LeetCode | Maximum Product Subarray
- LeetCode-Maximum Product Subarray
- C语言内存浅谈
- HDU -- 1398 Square Coins(母函数)
- 【剑指offer】八皇后问题
- 矩阵乘法模板
- 设计模式中的六大设计模式总结
- [LeetCode] Maximum Product Subarray
- HDU3117 Fibonacci Numbers【数学】
- arcmenu和raymenu
- opencv入门笔记之四 读写视频 捕捉移动点
- 矩阵乘法快速幂模板
- table-cell作用
- 2015.2.8实验室日记-纪逸清
- 《Hey程序员 你适合加入创业公司吗?》再补充
- Java IO流学习总结