• [算法]LeetCode 152:乘积最大子序列


    题目描述:

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

    示例 1:

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

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

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/maximum-product-subarray
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    题目思路:

    还是动态规划的问题。

    设置dp[nums.length][2]

    dp[i][0]表示必须包含第i个数值,前面这一段区间的乘积最大值。

    dp[i][1]表示必须包含第i个数值,前面这一段区间的乘积最小值。

    状态转移方程:

    dp[i][0] = Math.max(Math.max(dp[i - 1][0] * nums[i], dp[i - 1][1] * nums[i]), nums[i]);

    dp[i][1] = Math.min(Math.min(dp[i - 1][0] * nums[i], dp[i - 1][1] * nums[i]), nums[i]);

    题目代码:

    public int maxProduct(int[] nums) {
            int[][] dp = new int[nums.length][2];
            dp[0][0] = nums[0];//最大值
            dp[0][1] = nums[0];//最小值
            int max = nums[0];
    
            for (int i = 1; i < nums.length; i++) {
                dp[i][0] = Math.max(Math.max(dp[i - 1][0] * nums[i], dp[i - 1][1] * nums[i]), nums[i]);
                dp[i][1] = Math.min(Math.min(dp[i - 1][0] * nums[i], dp[i - 1][1] * nums[i]), nums[i]);
                if(dp[i][0] > max) {
                    max = dp[i][0];
                }
            }
            return max;
        }

    这代码还可以进一步优化,使得空间复杂度更小,因为每次值依赖上一次的结果,所以数组的行数只设为2即可。

    public int maxProduct(int[] nums) {
            int[][] dp = new int[2][2];
            dp[0][0] = nums[0];//最大值
            dp[0][1] = nums[0];//最小值
            int max = nums[0];
    
            for (int i = 1; i < nums.length; i++) {
                dp[i % 2][0] = Math.max(Math.max(dp[(i - 1) % 2][0] * nums[i], dp[(i - 1) % 2][1] * nums[i]), nums[i]);
                dp[i % 2][1] = Math.min(Math.min(dp[(i - 1) % 2][0] * nums[i], dp[(i - 1) % 2][1] * nums[i]), nums[i]);
                if(dp[i % 2][0] > max) {
                    max = dp[i % 2][0];
                }
            }
            return max;
        }
  • 相关阅读:
    03.分支结构
    02.语言元素
    开博的第一天
    http://mirrors.163.com/centos/7.6.1810/os/x86_64/repodata/repomd.xml: [Errno 14]
    spring boot配置spring-data-jpa的时候报错CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.NoSuchMethodError
    开机自动运行exe
    hibernate.QueryException: Legacy-style query parameters (`?`) are no longer supported 问题
    elasticSearch7____BUG
    idea开发web项目${pageContext.request.contextPath}出现错误
    进阶
  • 原文地址:https://www.cnblogs.com/DarrenChan/p/11076948.html
Copyright © 2020-2023  润新知