[LeetCode]152. Maximum Product Subarray
2024-08-31 02:49:35
This a task that asks u to compute the maximum product from a continue subarray. However, you need to watch
out the values' type contains positive, negative, zero.
I solved it using dynamic process in which there are two arrays to achieve the goal.
maxPro[i] : record the maximum product using nums[i] at end.
minPro[i] : record the minimum product using nums[i] at end.
Causing the neg and pos value types, we always can find the maximum product using the formula as below(maximum or minimum recording array):
- maxPro[i] = max3(nums[i], nums[i] * maxPro[i - 1], nums[i] * minPro[i - 1]);
- minPro[i] = min3(nums[i], nums[i] * maxPro[i - 1], nums[i] * minPro[i - 1]);
class Solution {
public:
int max3(int a, int b, int c){
return a > b? max(a, c): max(b, c);
} int min3(int a, int b, int c){
return a < b? min(a, c): min(b, c);
} int maxProduct(vector<int>& nums) {
vector<int>maxPro(nums.size(), );
vector<int>minPro(nums.size(), );
int ans = nums[];
for(int i = ; i < nums.size(); i ++){
if(i == ){
maxPro[] = nums[];
minPro[] = nums[];
}else{
maxPro[i] = max3(nums[i], nums[i] * maxPro[i - ], nums[i] * minPro[i - ]);
minPro[i] = min3(nums[i], nums[i] * maxPro[i - ], nums[i] * minPro[i - ]);
}
if(ans < maxPro[i]) ans = maxPro[i];
}
return ans;
}
};
最新文章
- scikit-learn 线性回归算法库小结
- clipboard_monitor_in_win7
- mac与php环境
- pushd
- 郝文菲get技能的经验--20155308
- 第二百三十八天 how can I 坚持
- POJ2492 A Bug&#39;s Life 带权并查集
- leetcode&mdash;triangle
- Eclipse:使用findBugs预先检测错误
- 两种解决Qt5显示中文乱码的方法(使用QStringLiteral和#pragma execution_character_set(";utf-8";)两种方法)
- 阐述linux IPC(两):基于socket进程间通信(下一个)
- 结构-行为-样式-JqueryUI拖放使用实例(全)
- java基本数据类型传递与引用传递区别
- Linux - rename 批量替换两种模式
- TVS(瞬间电压抑制器)
- tensorflow进阶篇-4(损失函数3)
- 解决Using 1.7 requires compiling with Android 4.4 (KitKat); currently using API 4
- Win10易升-在线升级工具
- 信号量 Linux函数 semget();semctl();semop();(转)
- Python 文件复制_bytes