My clear c++ solution


  • 0
    F
    class Solution {
    public:
        int maxProduct(vector<int>& nums) {
            if(nums.size()==0) return 0;
            long long dp_neg=0;
            long long dp_pos=0;
            long long max_pos=0;
            dp_neg=nums[0]>0?0:nums[0];
            dp_pos=nums[0]<0?0:nums[0];
            max_pos=nums[0];
            for(int i=1;i<nums.size();i++){
                if(nums[i]==0){
                    dp_neg=0;
                    dp_pos=0;
                    max_pos=max(max_pos,dp_pos);
                }
                else if(nums[i]>0){
                    dp_neg=dp_neg*nums[i];
                    dp_pos=fmaxl(dp_pos*nums[i],nums[i]);
                    if(dp_pos>0) max_pos=max(max_pos,dp_pos);
                }else{
                    long long temp=fminl(nums[i],dp_pos*nums[i]);
                    dp_pos=dp_neg*nums[i];
                    dp_neg=temp;
                    if(dp_pos>0) max_pos=max(max_pos,dp_pos);
                }
            }
            return max_pos;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.