zoukankan      html  css  js  c++  java
  • 152. Maximum Product Subarray

    Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

    Example 1:

    Input: [2,3,-2,4]
    Output: 6
    Explanation: [2,3] has the largest product 6.
    

    Example 2:

    Input: [-2,0,-1]
    Output: 0
    Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

    Approach #1: Math. [C++]

    class Solution {
    public:
        int maxProduct(vector<int>& nums) {
            int size = nums.size();
            if (size == 0) return size;
            
            int ans = nums[0];
            int curmax = nums[0];
            int curmin = nums[0];
            for (int i = 1; i < size; ++i) {
                int nextmax = curmax * nums[i];
                int nextmin = curmin * nums[i];
                curmax = max(nums[i], max(nextmax, nextmin));
                curmin = min(nums[i], min(nextmax, nextmin));
                ans = max(ans, max(curmax, curmin));
            }
            
            return ans;
        }
    };
    

      

    Analysis:

    Because nums is an integer array, so nums[i] > 1.  In this travel's every step(++i) we find the curmin and curmax and ans from 0 to current index(i), curmin can become curmax and curmax can become curmin, if both curmin and curmax are less than 0, nums[i] > 0 so nums[i] is the curmax.

    永远渴望,大智若愚(stay hungry, stay foolish)
  • 相关阅读:
    从零开始学asyncio(中)
    从零开始学asyncio(上)
    Java 后台多次获取requestBody
    Swift中的构造器
    CIDetector 相册识别二维码出错
    Swift-类和结构体
    定时器的使用以及注意事项
    ios-视图控制器跳转时生命周期的调用
    使用NSString的一些注意事项
    CALayer的锚点
  • 原文地址:https://www.cnblogs.com/h-hkai/p/10381307.html
Copyright © 2011-2022 走看看