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
.算法
從數組(至少包含一個數字)中找出一個連續的子數組,該子數組的乘積最大。數組
簡單動態規劃,
遞推公式
對於Product Subarray,要考慮到一種特殊狀況,即負數和負數相乘:
若是前面獲得一個較小的負數,和後面一個較大的負數相乘,獲得的反而是一個較大的數,如{2,-3,-7},
因此,咱們在處理乘法的時候,除了須要維護一個局部最大值,同時還要維護一個局部最小值
n<1說明輸入有錯,n大於0時
Fmax(0)=num[0]
Fmin(0)=num[0]
Fmax(n+1) = MAX(MAX(num[n+1]*Fmax(n), num[n+1]), num[n+1]*Fmin(n)) // 最大值
Fmin(n+1) = MIN(MIN(num[n+1]*Fmax(n), num[n+1]), num[n+1]*Fmin(n)) // 最小值,爲下一個新計算作準備spa
算法實現類.net
public class Solution { public int maxProduct(int[] nums) { if (nums == null || nums.length < 1) { throw new IllegalArgumentException(); } if (nums.length == 1) { return nums[0]; } int result = nums[0]; int fmax = nums[0]; int fmin = nums[0]; int prevMax; for (int i = 1; i < nums.length; i++) { prevMax = fmax; fmax = Math.max(Math.max(nums[i] * prevMax, nums[i]), nums[i] * fmin); fmin = Math.min(Math.min(nums[i] * prevMax, nums[i]), nums[i] * fmin); result = Math.max(result, fmax); } return result; } }