zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 152 乘积最大子序列

    152. 乘积最大子序列

    给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。

    示例 1:

    输入: [2,3,-2,4]
    输出: 6
    解释: 子数组 [2,3] 有最大乘积 6。
    示例 2:

    输入: [-2,0,-1]
    输出: 0
    解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。

    class Solution {
        public int maxProduct(int[] nums) {
            int max = Integer.MIN_VALUE, imax = 1, imin = 1; //一个保存最大的,一个保存最小的。
            for(int i=0; i<nums.length; i++){
                if(nums[i] < 0){ int tmp = imax; imax = imin; imin = tmp;} //如果数组的数是负数,那么会导致最大的变最小的,最小的变最大的。因此交换两个的值。
                imax = Math.max(imax*nums[i], nums[i]);
                imin = Math.min(imin*nums[i], nums[i]);
                
                max = Math.max(max, imax);
            }
            return max;
        }
    }
    
  • 相关阅读:
    奇偶数排序
    买房子
    首字母大写
    学分绩点
    加减乘除
    最简真分数
    Hdu 1058 Humble Numbers
    Hdu 1032 The 3n + 1 problem
    Hdu 1040 As Easy As A+B
    Hdu 1025 Constructing Roads In JGShining's Kingdom
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13075471.html
Copyright © 2011-2022 走看看