zoukankan      html  css  js  c++  java
  • 【LeetCode】152. 乘积最大子数组(DP)

    给你一个整数数组 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 temp = imax;
                    imax = imin;
                    imin = temp;
                }
                imax = Math.max(imax*nums[i], nums[i]);
                imin = Math.min(imin*nums[i], nums[i]); 
                max = Math.max(imax, max);
            }
            return max;
        }
    }
    
  • 相关阅读:
    win2008服务器信任问题
    切换cmd的目录
    c#后的完整cookie
    c#网络编程-第一章
    c#访问mysql数据库
    标准库hashlib模块
    标准库ConfigParser模块
    标准库shutil
    标准库 xml
    标准库shelve
  • 原文地址:https://www.cnblogs.com/whisperbb/p/12913956.html
Copyright © 2011-2022 走看看