Advertisement

算法作业解决最大乘积问题(DP)

阅读量:
在这里插入图片描述

该题目对时间复杂度提出了O(n)的要求,同时对空间复杂度限定为O(1),因此采用动态规划方法是最为直接的解决方式。考虑到题目中包含负数元素,在记录当前最大值的同时,也需同步记录最小值,以确保计算结果的准确性。

复制代码
    #include<iostream>
    #include<algorithm>
    #include<vector>
    
    using std::cin;
    using std::cout;
    using std::endl;
    using std::string;
    using std::vector;
    
    int maxProduct(vector<int>& arr, const int &n)
    {
    	//std::sort(arr, arr + 3);
    	std::sort(std::begin(arr), std::begin(arr) + 3);//对前面三个数据进行排序
    	int max1 = arr[2];
    	int max2 = ar

全部评论 (0)

还没有任何评论哟~