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;
        }
  • 相关阅读:
    source insight快捷键及使用技巧
    HTTP 状态码
    select poll epoll三者之间的比较
    服务器程序后台化以及守护进程的编写规范
    Linux 信号表
    Linux下有线无线网络配置------命令模式
    浅谈 qmake 之 pro、pri、prf、prl文件
    Python VUE 基础知识
    VUE 实现tab切换页面效果
    爬虫框架:scrapy
  • 原文地址:https://www.cnblogs.com/twoheads/p/11474434.html
Copyright © 2011-2022 走看看