• leetcode 152. Maximum Product Subarray


    Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

    Example 1:
    
    Input: [2,3,-2,4]
    Output: 6
    Explanation: [2,3] has the largest product 6.
    Example 2:
    
    Input: [-2,0,-1]
    Output: 0
    Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
    

    题意:求最大的连乘。

    思路:维护到当前位置的最大值和最小值。dp[i][0]表示最小值,dp[i][1]表示最大值。

    class Solution {
    public:
        int maxProduct(vector<int>& nums) {
            int n = nums.size();
            vector<vector<int> > dp(n, vector<int>(2));
            int ans = INT_MIN;
            if (n == 1) return nums[0];
            for (int i = 0; i < nums.size(); ++i) {
                if (i == 0) {
                    dp[i][1] = nums[i];
                    dp[i][0] = nums[i];
                } else {
                    if (nums[i] > 0) {
                        dp[i][1] = max(dp[i-1][1]*nums[i],nums[i]);
                        dp[i][0] = min(dp[i-1][0]*nums[i],nums[i]);
                    }
                    else {
                        dp[i][1] = max(dp[i-1][0]*nums[i], nums[i]);
                        dp[i][0] = min(dp[i-1][1]*nums[i], nums[i]);
                    }
                }
                ans = max(max(dp[i][0],dp[i][1]), ans);
            }
            return ans;
        }
    };
    

    这个代码还可以优化,比如不用数组,同时也不用判断nums[i]是大于0还是小于0

  • 相关阅读:
    session监听
    Ubuntu上安装MongoDB(转)
    JAVA中的集合(转)
    Iterator的用法(转)
    PHPExcel常用方法汇总(转)
    MongoDB的安装及在PHP中的配置Windows版
    [转载]使用FastReport 3.0及以上版本创建动态报表的几个技巧
    FastReport
    ZeosLib
    [转载]FastReport问题整理
  • 原文地址:https://www.cnblogs.com/pk28/p/9296691.html
Copyright © 2020-2023  润新知