Sharing my c++ sol;


  • 0
    P
    class Solution {
    public:
        int maxProduct(vector<int>& nums) {
            if(nums.size() == 0) return 0;
            int max_ending_here =nums[0];
            int min_ending_here =nums[0];
            int max_ending_sofar =nums[0];
            
            for( int i =1;i<nums.size();i++){
                if(nums[i] == 0){
                    max_ending_here =0;
                    min_ending_here =0;
                }
                else if (nums[i] > 0){
                    max_ending_here = max(max_ending_here*nums[i],nums[i]); 
                    min_ending_here = min(min_ending_here*nums[i],nums[i]);
                }
                else {
                    int temp = max_ending_here;
                    max_ending_here = max(min_ending_here*nums[i],nums[i]);
                    min_ending_here = min(temp*nums[i],nums[i]);
                }
                if (max_ending_here > max_ending_sofar)
                max_ending_sofar = max_ending_here;
            }
            return max_ending_sofar;
        }
    };

Log in to reply
 

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