題目描述:
找出一個序列中乘積最大的連續子序列(至少包含一個數)。
樣例:
比如, 序列 [2,3,-2,4]
中乘積最大的子序列為 [2,3]
,其乘積為6
。
第一種解法,同最大和子序列的暴力求解法,直接求出每個子序列的乘積,取最大值。
1 public class Solution { 2 /** 3 * @param nums: an array of integers 4 * @return: an integer 5 */ 6 public int maxProduct(int[] nums) { 7 8 int max = nums[0]; 9 int index = 1; 10 11 while(index <= nums.length){ 12 13 for(int i=0;i<=nums.length-index;i++){ 14 int product = 1; 15 for(int j=0;j<index;j++){ 16 product *= nums[i+j]; 17 } 18 19 if(product > max) 20 max = product; 21 } 22 index ++; 23 } 24 return max; 25 } 26 }
同樣,在數據量大的時候回超時,通過94%測試點。
第二種解法:
動態規划,每一步只需要記住其前一步的整數最大值和負數的最小值。代碼如下:
1 public class Solution { 2 /** 3 * @param nums: an array of integers 4 * @return: an integer 5 */ 6 public int maxProduct(int[] nums) { 7 int posmax=nums[0],negmax=nums[0],max=nums[0]; 8 9 for(int i=1;i<nums.length;i++){ 10 int tempPosMax = posmax; 11 int tempNegMax = negmax; 12 posmax = Math.max(nums[i],Math.max(nums[i]*tempPosMax,nums[i]*tempNegMax)); 13 negmax = Math.min(nums[i],Math.min(nums[i]*tempPosMax,nums[i]*tempNegMax)); 14 if(Math.max(posmax,negmax) > max){ 15 max = Math.max(posmax,negmax); 16 } 17 } 18 19 return max; 20 21 } 22 }