Leetcode: Maximum Product Subarray
来源:互联网 发布:阿里云服务器加固 编辑:程序博客网 时间:2024/06/06 12:51
题目:
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.
这里的Product是乘积的意思。这道题的tag是Dynamic Programming,所以同样是动态规划的思想,找出局部和全局的递推关系。
思路:这道题和上一道题:Maximum Subarray思路差不多。Maximum Subarray是求子数组和的最大值,这道题是求子数组乘积的最大值。计算最大的乘积同样要考虑负数的情况:一个很小的负数乘以一个负数,可能是一个很大的正数。所以这道题我们要设置两个局部最优变量,一个保存局部最大值,一个保存局部最小值(其实只有当这个局部最小值是负数的时候,才真正起作用)。
它们有如下关系:
copyMax = localMax
localMax = max(max(localMax * A[i], localMin * A[i]), A[i])
localMin = min(min(copyMax * A[i], localMin * A[i]), A[i])
globalMax = max(localMax, globalMax)
C++代码:
class Solution{public: int maxProduct(int A[], int n) { if (n <= 0) return 0; int globalMax = A[0]; int localMax = A[0]; int localMin = A[0]; int copyMax = localMax; for (int i = 1; i < n; i++) { copyMax = localMax; localMax = max(max(localMax * A[i], localMin * A[i]), A[i]); localMin = min(min(copyMax * A[i], localMin * A[i]), A[i]); globalMax = max(localMax, globalMax); } return globalMax; }};
C#代码:
public class Solution{ public int MaxProduct(int[] A) { if (A.Length <= 0) return 0; int globalMax = A[0]; int localMax = A[0]; int localMin = A[0]; int copyMax = localMax; for (int i = 1; i < A.Length; i++) { copyMax = localMax; localMax = Math.Max(Math.Max(localMax * A[i], localMin * A[i]), A[i]); localMin = Math.Min(Math.Min(copyMax * A[i], localMin * A[i]), A[i]); globalMax = Math.Max(globalMax, localMax); } return globalMax; }}
Python代码:
class Solution: # @param A, a list of integers # @return an integer def maxProduct(self, A): size = len(A) if size <= 0: return 0 globalMax = A[0] localMax = A[0] localMin = A[0] copyMax = localMax for i in range(1, size): copyMax = localMax localMax = max(max(localMax * A[i], localMin * A[i]), A[i]) localMin = min(min(copyMax * A[i], localMin * A[i]), A[i]) globalMax = max(globalMax, localMax) return globalMax
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++中派生类的认识
- 字符串分割(C++)
- java 反射通过get方法获得属性值
- Leetcode: Maximum Product Subarray
- 关于单例模式的一点思考
- 谈谈小米4的win10---一个windows phone 用户2年的瞎扯
- Sicily 13907. Dice Game
- Yii2 使用七 Model添加非表字段属性
- 在窗口中贴图
- android Monkey测试(2)
- poj 2777
- scanf()、getch()、getchar()、getc()、gets()