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

        This a task that asks u to compute the maximum product from a continue subarray. However, you need to watch 

    out the values' type contains positive, negative, zero.

        I solved it using dynamic process in which there are two arrays to achieve the goal.

        maxPro[i] : record the maximum product using nums[i] at end.

        minPro[i] : record the minimum product using nums[i] at end.

        Causing the neg and pos value types, we always can find the maximum product using the formula as below(maximum or minimum recording array):

    •   maxPro[i] = max3(nums[i], nums[i] * maxPro[i - 1], nums[i] * minPro[i - 1]);
    •   minPro[i] = min3(nums[i], nums[i] * maxPro[i - 1], nums[i] * minPro[i - 1]);
    class Solution {
    public:
        int max3(int a, int b, int c){
            return a > b? max(a, c): max(b, c);
        }
        
        int min3(int a, int b, int c){
            return a < b? min(a, c): min(b, c); 
        }
        
        int maxProduct(vector<int>& nums) {
            vector<int>maxPro(nums.size(), 0);
            vector<int>minPro(nums.size(), 0);
            int ans = nums[0];
            for(int i = 0; i < nums.size(); i ++){
                if(i == 0){
                    maxPro[0] = nums[0];
                    minPro[0] = nums[0];
                }else{
                    maxPro[i] = max3(nums[i], nums[i] * maxPro[i - 1], nums[i] * minPro[i - 1]);
                    minPro[i] = min3(nums[i], nums[i] * maxPro[i - 1], nums[i] * minPro[i - 1]);
                }
                if(ans < maxPro[i]) ans = maxPro[i];
            }
            return ans;
        }
    };
  • 相关阅读:
    一些常用的接口地址
    1-项目启动
    事件处理优化
    如何javascript获取css中的样式
    mysql编程--创建函数出错的解决方案
    mysql编程---函数
    mysql---数据控制语言(用户及其权限管理)
    php与mysql的常规使用
    php数组的使用
    php函数的使用
  • 原文地址:https://www.cnblogs.com/luntai/p/5734688.html
Copyright © 2011-2022 走看看