首页 > 代码库 > 【LeetCode】【Solution】Maximum Product Subarray
【LeetCode】【Solution】Maximum Product Subarray
【题目】
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; }
【声明】本博客只是用于学习和交流,如不小心侵犯了您的权益,请联系本人,我会及时处理,谢谢!
【LeetCode】【Solution】Maximum Product Subarray
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。