zoukankan      html  css  js  c++  java
  • 【leetcode-152】 乘积最大子序列

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

    示例 1:

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

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

    由于存在负数,那么会导致最大的变最小的,最小的变最大的。因此还需要维护当前最小值imin

    max表示以当前节点为终结节点的最大连续子序列乘积 min表示以当前节点为终结节点的最小连续子序列乘积

    我们只要记录前i的最小值, 和最大值, 那么 dp[i] = max(nums[i] * pre_max, nums[i] * pre_min, nums[i])

    class Solution {
        public int maxProduct(int[] nums) {
            if (nums == null || nums.length == 0) return 0;
            int res = nums[0];
            int pre_max = nums[0];
            int pre_min = nums[0];
            for (int i = 1; i < nums.length; i++) {
                int cur_max = Math.max(Math.max(pre_max * nums[i], pre_min * nums[i]), nums[i]);
                int cur_min = Math.min(Math.min(pre_max * nums[i], pre_min * nums[i]), nums[i]);
                res = Math.max(res, cur_max);
                pre_max = cur_max;
                pre_min = cur_min;
            }
            return res;
        }
    }

    我:

        public int maxProduct(int[] nums) {
            if (nums == null || nums.length == 0) {
                return 0;
            }
            int max = nums[0];
            int pre_max = nums[0];
            int pre_min = nums[0];
            for (int i=1;i<nums.length;i++) {
                int cur_max = Math.max(Math.max(pre_max*nums[i],pre_min*nums[i]),nums[i]);
                int cur_min = Math.min(Math.min(pre_max*nums[i],pre_min*nums[i]),nums[i]);
                max = Math.max(max,cur_max);
                pre_max = cur_max;
                pre_min = cur_min;
            }
            return max;
        }
  • 相关阅读:
    win10系统设置指定程序开机自启
    PyCharm 2020.1 x64 专业版破解【亲测有效】
    xampp_mysql数据库root登录报错1045-Access denied for user 'root'@'localhost' (using password:YES)
    关于 Tomcat 启动时,解决控制台输出日志乱码问题的方案
    1.css选择器
    5.canvas
    4.音频与视频
    3.form表单
    淘宝店铺设计
    2.html5新布局元素
  • 原文地址:https://www.cnblogs.com/twoheads/p/11474434.html
Copyright © 2011-2022 走看看