子数组最大乘积
来源:互联网 发布:李炎恢php第四季下载 编辑:程序博客网 时间:2024/04/29 01:03
给定一个double类型的数组arr,其中的元素可正可负可0,返回子数组累乘的最大乘积。例如arr=[-2.5,4,0,3,0.5,8,-1],子数组[3,0.5,8]累乘可以获得最大的乘积12,所以返回12。
解析:此题可以运用动态规划解决
设f[i]表示以i为结尾的最大值,g[i]表示以i结尾的最小值,那么
f[i+1] = max{f[i]*arr[i+1], g[i]*arr[i+1],arr[i+1]} ,只有这三种情况。
考虑到f[i],g[i]只和i-1有关,那么可以用局部变量即可搞定,而不用使用数组。
C++风格代码:
class Solution { public: double maxProduct(vector<double> arr) { if(arr.size() == 0) return 0; double minVal = arr[0]; double maxVal = arr[0]; double rtn = arr[0]; double tmpMax = 0; double tmpMin = 0; for(int i = 1; i < arr.size(); i++) { //cout << "max\t" << maxVal << endl; //cout << "min\t" << minVal << endl; tmpMax = max(maxVal * arr[i], minVal * arr[i]); tmpMin = min(maxVal * arr[i], minVal * arr[i]); maxVal = max(tmpMax, arr[i]); minVal = min(tmpMin, arr[i]); rtn = max(rtn, maxVal); } return rtn; } };或者另一种C代码:
// 子数组的最大乘积int MaxProduct(int *a, int n){ int maxProduct = 1; // max positive product at current position int minProduct = 1; // min negative product at current position int r = 1; // result, max multiplication totally for (int i = 0; i < n; i++) { if (a[i] > 0) { maxProduct *= a[i]; minProduct = min(minProduct * a[i], 1); } else if (a[i] == 0) { maxProduct = 1; minProduct = 1; } else // a[i] < 0 { int temp = maxProduct; maxProduct = max(minProduct * a[i], 1); minProduct = temp * a[i]; } r = max(r, maxProduct); } return r;}
1 1
- 子数组最大乘积
- 最大子数组乘积
- 最大乘积子数组
- 最大子数组乘积
- 子数组最大乘积
- 子数组最大乘积
- 最大乘积子数组
- 子数组最大乘积
- 最大子数组乘积
- 子数组的最大乘积
- 子数组的最大乘积
- 子数组的最大乘积
- 子数组的最大乘积
- 子数组的最大乘积
- 2.13子数组最大乘积
- 求子数组最大乘积
- 子数组的最大乘积
- 子数组的最大乘积
- pthread_attr_init 线程属性
- (Windows Maven项目)Jedis数据库的安装和操作实现
- 学习meteor之后的总结
- JSP乱码
- HDU 5284 wyh2000 and a string problem(查找字符)
- 子数组最大乘积
- CORS(跨域资源共享)简介。。。
- uva122_二叉树的层次历遍
- HTML5多媒体素材的应用
- anroid studio快捷键
- OC类 之 NSString
- [基本实验] 探测Web目录结构和隐藏的敏感文件
- OC的字符串
- Objective-C的指令