zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    第二百零一天 how can I坚持
    第一百九十七-第二百天 how can I 坚持
    第一百九十六天 how can I 坚持
    第一百九十五天 how can I 坚持
    第一百九十四天 how can I坚持
    第一百九十三天 how can I 坚持
    第一百九十二天 how can I 坚持
    第一百九十一天 how can I 坚持
    杭电2085--核反应堆(打表)
    杭电1799--循环多少次
  • 原文地址:https://www.cnblogs.com/xiaocainiao2hao/p/5361070.html
Copyright © 2011-2022 走看看