Straightforward implementation of the suggested solution in 10 lines of C++


  • 1

    The only non-trivial thing involved in the implementation is to use a variable (ans) to keep track of the maximum product that has been seen, and update it whenever necessary (ans = max(ans, ff)).

        int maxProduct(vector<int>& nums) {
            int f = nums[0], g = nums[0], ans = nums[0];
            for (int i = 1; i < nums.size(); i++) {
                int ff = max(f * nums[i], max(g * nums[i], nums[i]));
                int gg = min(g * nums[i], min(f * nums[i], nums[i]));
                ans = max(ff, ans); f = ff; g = gg;
            } 
            return ans;
        }

Log in to reply
 

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