【LeetCode】【Solution】Maximum Product Subarray
来源:互联网 发布:淘宝模拟试衣服 编辑:程序博客网 时间:2024/05/16 16:05
【题目】
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
.
参考 http://segmentfault.com/blog/riodream/1190000000691766
public class Solution { public int maxProduct(int[] A) { if (A.length == 0) return 0; if (A.length == 1) return A[0]; int max_ending_here = 0; int min_ending_here = 0; int max_so_far = 0; for (int i = 0; i < A.length; i++) { if (A[i] > 0) { max_ending_here = Math.max(max_ending_here * A[i], A[i]); min_ending_here = Math.min(min_ending_here * A[i], A[i]); } else if (A[i] == 0) { max_ending_here = 0; min_ending_here = 0; } else { int temp = max_ending_here; max_ending_here = Math.max(min_ending_here*A[i], A[i]); min_ending_here = Math.min(temp * A[i], A[i]); } if (max_ending_here > max_so_far) { max_so_far = max_ending_here; } } return max_so_far; }}
【标准Solution】
Let us denote that:
f(k) = Largest product subarray, from index 0 up to k.
Similarly,
g(k) = Smallest product subarray, from index 0 up to k.
Then,
f(k) = max( f(k-1) * A[k], A[k], g(k-1) * A[k] )g(k) = min( g(k-1) * A[k], A[k], f(k-1) * A[k] )上面就是动规方程。
public int maxProduct(int[] A) { assert A.length > 0; int max = A[0], min = A[0], maxAns = A[0]; for (int i = 1; i < A.length; i++) { int mx = max, mn = min; max = Math.max(Math.max(A[i], mx * A[i]), mn * A[i]); min = Math.min(Math.min(A[i], mx * A[i]), mn * A[i]); maxAns = Math.max(max, maxAns); } return maxAns;}
【声明】本博客只是用于学习和交流,如不小心侵犯了您的权益,请联系本人,我会及时处理,谢谢!
0 0
- 【LeetCode】【Solution】Maximum Product Subarray
- 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
- mysql的局域网连接
- Android平台下基于XMPP的IM研究(二 MultiUserChat 聊天室)
- 博客感想-1
- 【.Net码农】huangxincheng一线码农系列--wcf系列学习5天速成
- MongoDB资料汇总专题
- 【LeetCode】【Solution】Maximum Product Subarray
- A + B Again
- web.xml配置详解
- matlab--颜色空间的转换
- 【转】C语言中#if #else 有什么作用?
- 机器学习之&&Andrew Ng课程复习--- 神经网络3
- 根据选择的日期字符串判断今天明天后天
- 如何进行Linux Kernel 开发
- 实现一个简单的手势解锁