Maximum Product Subarray--leetcode
来源:互联网 发布:网络系统集成课程设计 编辑:程序博客网 时间:2024/05/22 05:01
原题链接:https://oj.leetcode.com/problems/maximum-product-subarray/
题目大意:求一个序列的最大积连续子序列。
解题方法:一维动态规划。
思路:看到这道题,很容易联想到最大和连续子数组那道题,忘了的可以看一下https://oj.leetcode.com/problems/maximum-subarray/,或者看我的上一篇博文。但是这道题与最大和连续子序列的不同是,仅仅维护以下标i元素结尾的最大积(和)子序列是不行的,因为乘积与正负有关,负负得正是吧。这就需要我们在维护以下标i元素结尾的最大积子序列的同时,维护以下标i元素结尾的最小积子序列。这样递推公式就很同意得到,如下:
max_product[i+1]=max(max_product[i]*A[i+1],min_product[i]*A[i+1],A[i+1]),即三者中的最大值。
min_product[i+1]=max(max_product[i]*A[i+1],min_product[i]*A[i+1],A[i+1]),即三者中的最小值。
为求的最大积子序列,我们需要维护一个量,来求得max_product[]数组的最大值。
时间复杂度:由于遍历数组一边,所以为O(N),
空间复杂度:只需要维护几个量就可以,所以为O(1)
class Solution {public: int maxProduct(int A[], int n) { if(n<=0) return 0; int maxherepre = A[0]; int minherepre = A[0]; int maxsofar = A[0]; int maxhere, minhere; for (int i = 1; i < n; i++) { maxhere = max(max(maxherepre * A[i], minherepre * A[i]), A[i]); minhere = min(min(maxherepre * A[i], minherepre * A[i]), A[i]); maxsofar = max(maxhere, maxsofar); maxherepre = maxhere; minherepre = minhere; } return maxsofar; } int max(int i,int j){ return i<j?j:i; } int min(int i,int j){ return i<j?i:j; }};
最大积在最大和连续子序列的基础上需要我们维护更多的量,是理解动态规划方法的一道不错的题。
7 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
- Windows打包安装程序
- Java四种线程池的使用
- 图片圆角设置
- 快乐;水电费快乐撒地方
- java中HashMap学习
- Maximum Product Subarray--leetcode
- 在sql server中实现查找一个月中有多少星期天
- Java中信号量 Semaphore
- 竞态条件与临界区
- RCP获取资源工具类
- JAVA加密算法实现用例 消息摘要
- 啊是的覅就看来就阿桑地方快乐撒地方
- JAVA加密算法实现用例 数字签名
- 禁止EditText 输入粘贴版内容