算法题目--Maximum Product Subarray

题目来源

https://leetcode.com/problems/maximum-product-subarray/description/

题目描述

Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

心路历程

动态规划问题。使用两个数组记录从开始到i的乘积最大值还有最小值。每次最大值从当前值,当前值与上一轮的最大值的乘积,当前值与上一轮的最小值的乘积中选最大的产生。最小值同理。

解决方案

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int len = nums.size();
        int * _max = new int[len];
        int * _min = new int[len];
        int result = nums[0];
        _max[0] = _min[0] = nums[0];
        for (int i = 1; i < len; i++) {
            _max[i] = max(max(_max[i - 1] * nums[i], _min[i - 1] * nums[i]), nums[i]);
            _min[i] = min(min(_max[i - 1] * nums[i], _min[i - 1] * nums[i]), nums[i]);
            result = max(result, _max[i]);
        }
        return result;
    }
};
int main() {
    vector<int> nums = { 2, 3, -2, 4 };
    Solution solution;
    cout << solution.maxProduct(nums) << endl;
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值