leetcode 152 —— Maximum Product Subarray
2015-08-18 16:46
363 查看
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array
the contiguous subarray
思路:用两个数组,一个存放整数乘积,一个存放负数乘积。
class Solution {
public:
int maxProduct(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
if (n == 1) return nums[0];
vector<int> pos(n, 0); //最大正数
vector<int> neg(n, 0); //最大负数
pos[0] = nums[0] > 0 ? nums[0] : 0;
neg[0] = nums[0] < 0 ? nums[0] : 0;
for (int i = 1; i < n; i++) {
if (nums[i] == 0) {
pos[i] = 0;
neg[i] = 0;
}
else if(nums[i]>0){
pos[i] = pos[i - 1] == 0 ? nums[i] : pos[i - 1] * nums[i];
neg[i] = neg[i - 1] == 0 ? 0 : neg[i-1] * nums[i];
}
else {
pos[i] = neg[i - 1] == 0 ? 0 : neg[i-1] * nums[i];
neg[i] = pos[i - 1] == 0 ? nums[i] : pos[i - 1] * nums[i];
}
}
int maxProduct = INT_MIN;
for (int i = 0; i < n; i++) {
maxProduct = maxProduct > pos[i] ? maxProduct : pos[i];
}
return maxProduct;
}
};
For example, given the array
[2,3,-2,4],
the contiguous subarray
[2,3]has the largest product =
6.
思路:用两个数组,一个存放整数乘积,一个存放负数乘积。
class Solution {
public:
int maxProduct(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
if (n == 1) return nums[0];
vector<int> pos(n, 0); //最大正数
vector<int> neg(n, 0); //最大负数
pos[0] = nums[0] > 0 ? nums[0] : 0;
neg[0] = nums[0] < 0 ? nums[0] : 0;
for (int i = 1; i < n; i++) {
if (nums[i] == 0) {
pos[i] = 0;
neg[i] = 0;
}
else if(nums[i]>0){
pos[i] = pos[i - 1] == 0 ? nums[i] : pos[i - 1] * nums[i];
neg[i] = neg[i - 1] == 0 ? 0 : neg[i-1] * nums[i];
}
else {
pos[i] = neg[i - 1] == 0 ? 0 : neg[i-1] * nums[i];
neg[i] = pos[i - 1] == 0 ? nums[i] : pos[i - 1] * nums[i];
}
}
int maxProduct = INT_MIN;
for (int i = 0; i < n; i++) {
maxProduct = maxProduct > pos[i] ? maxProduct : pos[i];
}
return maxProduct;
}
};
相关文章推荐
- 欢迎使用CSDN-markdown编辑器
- OpenGL4.3如何管理buffer中的数据的(二)
- DNS域名解析简介
- [DP]0817-08基础DP
- hdoj 1596 find the safest road
- Android Fragment 真正的完全解析(下)
- 杭电 2680 Choose the best route(dijkstra)
- Java连接池
- TCP/IP体系结构简介
- PLSQL配置数据库的方式
- 微信公众号开发之微信支付
- 2015年邮件营销人员最值得关注的10个焦点
- 黑马程序员_TCPUDP
- Load Asset Bundle in Editor
- select2组件
- C++函数调用详解
- C++函数调用详解
- C++函数调用详解
- C++函数调用详解
- C++函数调用详解