LintCode-乘积最大子序列

题目描述:

  找出一个序列中乘积最大的连续子序列(至少包含一个数)。

样例:

  比如, 序列 [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 }
原文地址:https://www.cnblogs.com/xiaocainiao2hao/p/5361070.html