Untitled

mail@pastecode.io avatar
unknown
plain_text
15 days ago
634 B
5
Indexable
Never
class Solution {
public:
    using ll = long long;
    int maxProduct(vector<int>& nums) {
        ll maxi = 1, mini = 1;
        ll ans = INT_MIN, n = nums.size();
        for(auto num: nums){
            if(num < 0)
                swap(maxi, mini);//Critical
            maxi = max(num*maxi, (ll)num);//Should update, must choose or not choose
            mini = min(num*mini, (ll)num);
            if(mini < 0 && num > (INT_MIN+1)/mini){
                mini = 1;
                maxi = 1;
            }
            ans = max(ans, maxi);
        }
        return ans;
    }
    //Time O(N)
    //Space O(1)
};
Leave a Comment