Leetcode Maximum Product Subarray
来源:互联网 发布:铁翼雄风 知乎 编辑:程序博客网 时间:2024/06/15 18:03
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;}
0 0
- Maximum Product Subarray 【LeetCode】
- [LeetCode] Maximum Product Subarray
- leetcode-Maximum Product Subarray
- Maximum Product Subarray -- LeetCode
- LeetCode-Maximum Product Subarray
- [LeetCode]Maximum Product Subarray
- [LeetCode]Maximum Product Subarray
- 【LeetCode】Maximum Product Subarray
- leetcode:Maximum Product Subarray
- leetcode: Maximum Product Subarray
- Leetcode: Maximum Product Subarray
- [LeetCode]Maximum Product Subarray
- Leetcode Maximum Product Subarray
- [Leetcode]Maximum Product Subarray
- Leetcode--Maximum Product Subarray
- Maximum Product Subarray [leetcode]
- LeetCode | Maximum Product Subarray
- LeetCode-Maximum Product Subarray
- P2P第三方资金托管平台
- redis 启动警告及处理
- hdoj1044,Collect More Jewels
- 第二章 数据库的操作
- 索引器(封装一个数组类)改params关键字
- Leetcode Maximum Product Subarray
- 《剑指offer》整数中1出现的次数(从1到n整数中1出现的次数)
- 使用HttpURLConnection(实现单线程多线程下载)
- UVa 11214:Guarding the Chessboard(DFS)
- java多态初步
- matlab中linspace函数
- 飘雪作业——index.html
- ListView 分页效果
- 0基础自学《第一行代码》