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: