lintCode【91】乘积最大子序列

描述:

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

样例 :

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

思路:因为涉及到正负,所以要保存最小值和最大值两种情况,因为负负得正。最小值的比较包括nums[i]、min*nums[i] 、max*nums[i],最大值与此相同,其实最大值就是正数,最小值是负数,中间值没必要记录。

public class Solution {
    /**
     * @param nums: an array of integers
     * @return: an integer
     * 机智如我
     */
    public int maxProduct(int[] nums) {
        // write your code here
        if(nums == null || nums.length == 0){
            return 0;
        }
        if(nums.length == 1) return nums[0];
        int max = 1;
        int min = 1;
        int result = 1;
        for(int i = 0;i<nums.length;i++){
            int temp = min;
            min = Math.min(Math.min(min * nums[i] , max * nums[i]) , nums[i]);
            max = Math.max(Math.max(temp * nums[i] , max * nums[i]) , nums[i]);
            if(max>result){
                result = max;
            }
        }
        return result;
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值