Leetcode Maximum Product Subarray

Leetcode Maximun Product Subarray 相关算法实现,使用dp算法完成问题,并提供测试,提供两种实现,一种为常规的,别一种为最大子串积的快速解决方法,代码如下。

常规解法:O(n^2)

#include <iostream>
#include <vector>
using namespace std;

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int len = nums.size();
        vector<vector<vector<int> > > re(len, vector<vector<int> >(len, vector<int>(2, 0)));
        re.resize(len);
        for (int i = 0; i < len; i ++) {
            re[i][i][0] = nums[i];
            re[i][i][1] = nums[i];
        }
        for (int i = 1; i < len; i ++) {
            for (int j = 0; j < len - i; j ++ ) {
                int max = re[j][j][0];
                for (int k = 0; k < i; k ++) {
                    int temp = re[j][j + k][1] * re[j + k + 1][j + i][1];
                    max = maxOfFour(max, temp, re[j][j + k][0], \
                            re[j + k + 1][j + i][0]);
                }
                re[j][j + i][0] = max;
                re[j][j + i][1] = re[j][j][1] * re[j + 1][j + i][1];
            }
        }
        return re[0][len - 1][0];
    }

    int maxOfFour(int a, int b, int c, int d) {
        int max = a;
        if (b > max) {
            max = b;
        }
        if (c > max) {
            max = c;
        }
        if (d > max) {
            max = d;
        }
        return max;
    }
};


int main() {
    vector<int> a;
    a.push_back(-1);
    a.push_back(2);
    a.push_back(0);
    a.push_back(-4);
    a.push_back(3);
    a.push_back(-2);
    Solution so;
    int re = so.maxProduct(a);
    cout<<"The result is :"<<re<<endl;
    return 0;
}

由本问题特性实现的算法:O(n)

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int len = nums.size();
        int reMax = nums[0];
        int reMin = nums[0];
        int re = nums[0];
        for (int i = 1; i < len; i ++) {
            int temp = reMax;
            reMax = max(max(nums[i], reMin * nums[i]), reMax * nums[i]);
            reMin = min(min(nums[i], reMin * nums[i]), temp * nums[i]);
            re = max(reMax, re);
        }
        return re;
    }
};

int main() {
    vector<int> a;
    a.push_back(-1);
    a.push_back(0);
    a.push_back(3);
    a.push_back(-4);
    Solution so;
    int re = so.maxProduct(a);
    cout<<"The result is :"<<re<<endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值