动态规划--最大乘积子序列

来源:互联网 发布:知乎手机上网页版 编辑:程序博客网 时间:2024/06/05 17:35

需求:

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

比如, 序列 [2,3,-2,4] 中乘积最大的子序列为 [2,3] ,其乘积为6

分析:

1、O(n^2)

暴力求解,变量数组每个元素,求其所有的子序列的乘积,并更新乘积最大值。

2、O(n)

采用动态规划思想,类似于求最大和子序列,但是乘法和加法不同,确定某个元素为结尾的子序列最大和时,需要看其前一个元素为结尾子序列最大和是否是正数,而对于乘法,需要考虑该元素、该元素乘以前一个元素为结尾的子序列最大最小值的最大值。为了表述清楚,描述如下:

原始数组是int nums[],对于数组nums的每个元素,对应两个变量,posmax代表以nums[i]为结尾的子序列乘积的最大值,negmax代表以nums[i]为结尾的子序列乘积的最小值,而最大乘积是二者的最大值。所以初始时,posmax=nums[0],negmin=nums[0],max=nums[0]。遍历数组元素nums[i],更新posmax=max{nums[i], nums[i]*posmax(nums[i-1]对应的), nums[i]*negmin(nums[i-1]对应的)},negmin=min{nums[i], nums[i]*posmax(nums[i-1]对应的), nums[i]*negmin(nums[i-1]对应的)},更新max,max=max{max, posmax, negmin}。

代码:

public class Solution {    /*     * @param nums: An array of integers     * @return: An integer     */    public int maxProduct(int[] nums) {        // write your code here        //如果是null那么返回0        if(nums == null || nums.length == 0) {            return 0;        }                /*        //思路一:暴力求解        //遍历数组元素,每个元素维护一个变量,代表当前的乘积        //全局变量max,最大的乘积        int max = nums[0];                for(int i = 0; i < nums.length; i++) {            int mul = 1;                        for(int j = i; j < nums.length; j++) {                mul *= nums[j];                                if(mul > max) {                    max = mul;                }            }        }                return max;        */                //思路二:动态规划        //遍历数组,每个元素对应以该元素为结尾的子序列的最大值和最小值两个变量,更新乘积最大值        int posmax = nums[0], negmin = nums[0], max = nums[0];                for(int i = 1; i < nums.length; i++) {            int pre_posmax = posmax;            int pre_negmin = negmin;                        posmax = Math.max(nums[i], Math.max(nums[i]*pre_posmax, nums[i]*pre_negmin));            negmin = Math.min(nums[i], Math.min(nums[i]*pre_posmax, nums[i]*pre_negmin));                        if(Math.max(posmax, negmin) > max) {                max = Math.max(posmax, negmin);            }                    }                return max;                }}


原创粉丝点击