程序员人生 网站导航

LeetCode Maximum Product Subarray

栏目:互联网时间:2014-12-14 08:40:15

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,⑵,4],

the contiguous subarray [2,3] has the largest product = 6.

思路分析:这题与LeetCode Maximum Subarray类似,只是要注意两个负数的乘积可能变成1个很大的正数,因此要同时保护maxLocal和minLocal和maxGlobal,初值为A[0],以后从A[1]开始遍历,maxLocal取A[i],A[i]*maxLocal.A[i]*minLocal中的最大,minLocal取A[i],A[i]*maxLocal.A[i]*minLocal中的最小,maxGlobal则是始终保存maxLocal中的最大值。要注意,更新minLocal时要用到原始的maxLocal的拷贝,而不是更新以后的值。

AC Code:

public class Solution { public int maxProduct(int[] A) { //01:42 if(A.length == 0) return 0; if(A.length == 1) return A[0]; int maxLocal = A[0]; int minLocal = A[0]; int maxGlobal = A[0]; for(int i = 1; i < A.length; i++){ int maxCopy = maxLocal; maxLocal = Math.max(Math.max(A[i], A[i] * maxLocal), A[i] * minLocal); minLocal = Math.min(Math.min(A[i], A[i] * maxCopy), A[i] * minLocal); maxGlobal = Math.max(maxGlobal, maxLocal); } return maxGlobal; //01:47 } }


------分隔线----------------------------
------分隔线----------------------------

最新技术推荐