O(n) time O(1) space C++ solution


  • 5
    K
    class Solution {
    public:
        int maxProduct(vector<int>& nums) {
            assert (!nums.empty());
            int curMax = nums[0], curMin = nums[0], res = nums[0];
            for (int i = 1; i < nums.size(); ++i) {
                int mx = curMax, mn = curMin;
                curMax = max(max(mx * nums[i], mn * nums[i]), nums[i]);
                curMin = min(min(mx * nums[i], mn * nums[i]), nums[i]);
                res = max(res, curMax);
            }
            return res;
        }
    };

  • 0
    L

    This is my simple answer using erase() and remove() together.
    Thanks!

    class Solution {
    public:
    int removeElement(vector<int>& nums, int val) {
    nums.erase(std::remove(nums.begin(), nums.end(), val), nums.end());
    return nums.size();
    }
    };


  • 0
    Y

    The first one won't work even if there is no '0'. Try [2,-3,-4,-5,6].


  • 0
    K

    you are right, my understanding has flaws, and i've deleted it, thanks!


Log in to reply
 

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