zoukankan      html  css  js  c++  java
  • LeetCode 152. Maximum Product Subarray

    Find the contiguous subarray within an array (containing at least one number) which has the largest product.

    For example, given the array [2,3,-2,4],
    the contiguous subarray [2,3] has the largest product = 6.

    class Solution {
    public:
        const int inf = -9999999;
        int maxProduct(vector<int>& nums) {
            int ans = inf;
            vector<int> postive(nums.size()+1, inf);
            vector<int> negtive(nums.size()+1, inf);
            for(int i=0; i<nums.size(); i++){
                if( nums[i]<0){
                    postive[i+1] = negtive[i] == inf ? inf : negtive[i] * nums[i];
                    negtive[i+1] = postive[i] == inf ? nums[i] : min( nums[i], nums[i]*postive[i]);
                }else{
                    postive[i+1] = postive[i] == inf ? nums[i] : max( nums[i], nums[i]*postive[i]);
                    negtive[i+1] = negtive[i] == inf ? inf : negtive[i] * nums[i];
                }
                ans = max( ans ,max(postive[i+1], negtive[i+1]));
            }
            return ans;
        }
    };
    
  • 相关阅读:
    idea自带的maven
    面试题汇总
    mybatis参数处理
    tips
    mybatis-config.xml
    helloWorld程序
    idea遇到的问题汇总
    PL/SQL批量执行SQL脚本文件
    Iframe跳转本地项目
    angular video播放问题
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/10055781.html
Copyright © 2011-2022 走看看