[LeetCode] Maximum Product Subarray

来源:互联网 发布:国家实行网络什么战略 编辑:程序博客网 时间:2024/06/08 13:26

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.


代码很短,但其实逻辑还是有点绕额:

public class Solution {//注意  因为有0的情况 随意分正负讨论是很复杂的 //状态转换方程如下: //max[i]=Math.max(Math.max(min[i-1]*a[i],max[i-1]*a[i]),a[i]);//min[i]=Math.min(Math.min(min[i-1]*a[i],max[i-1]*a[i]),a[i]);    public int maxProduct(int[] a) {if(a.length==0) return 0;int[] max=new int[a.length];int[] min=new int[a.length];int re=max[0]=min[0]=a[0];for(int i=1;i<a.length;i++){max[i]=Math.max(Math.max(min[i-1]*a[i],max[i-1]*a[i]),a[i]);min[i]=Math.min(Math.min(min[i-1]*a[i],max[i-1]*a[i]),a[i]);re=Math.max(re,max[i]);}return re;}}