当前位置:网站首页>leetcode:152. 乘积最大子数组
leetcode:152. 乘积最大子数组
2022-08-03 02:04:00 【OceanStar的学习笔记】
题目来源
题目描述

题目解析
- 对于子数组问题,其dp一般定义为:必须以nums[i]结尾的子数组…,然后对于每一个dp[i]有两种选择:
- 仅仅选择nums[i]
- 以nums[i]为基地,向前扩展
- 这里特殊的是:两个负数相乘可能会变得很大,负数*正数可能会变得很小。所以我们需要同时维护两个值-----最大值、最小值
class Solution {
struct info{
int max;
int min; // 两个负数相乘可能变得很大
info(){
max = INT32_MIN;
min = INT32_MAX;
}
};
public:
int maxProduct(vector<int>& nums) {
int N = nums.size();
if(N == 0){
return 0;
}
//该子数组中至少包含一个数字
if(N == 1){
return nums[0];
}
std::vector<info> dp(N); //必须以num[i]结尾的最大乘积子数组
dp[0].min = nums[0];
dp[0].max = nums[0];
int ans = nums[0];
for (int i = 1; i < N; ++i) {
int p1 = nums[i];
int p2 = nums[i] * dp[i - 1].min; // 两个负数相乘可能变得很大
int p3 = nums[i] * dp[i - 1].max; // 测试用例的答案是一个 32-位 整数。 不会溢出
dp[i].min = std::min(p1, std::min(p2, p3));
dp[i].max = std::max(p1, std::max(p2, p3));
ans = std::max(ans, dp[i].max);
}
return ans;
}
};
上面,因为dp[i]仅仅依赖dp[i-1],所以:
class Solution {
public:
int maxProduct(vector<int>& nums) {
int N = nums.size();
if(N == 0){
return 0;
}
int pMin = nums[0];
int pMax = nums[0];
int ans = nums[0];
for (int i = 1; i < N; ++i) {
int cMin = std::min(nums[i], std::min(nums[i] * pMin, nums[i] * pMax));
int cMax = std::max(nums[i], std::max(nums[i] * pMin, nums[i] * pMax));
ans = std::max(ans, cMax);
pMin = cMin;
pMax = cMax;
}
return ans;
}
};
边栏推荐
- [Arduino] Reborn Arduino Monk (2)----Arduino Language
- iNFTnews | 元宇宙的潜力:一股推动社会进步的力量
- [Arduino] Reborn Arduino Monk (3)----Arduino function
- qt opengl 使用不同的颜色绘制线框三角形
- win下使用vscode+wsl2
- The LVS load balancing cluster and the deployment of the LVS - NAT experiment
- 常见钓鱼手法及防范
- 在排列中求lcs
- JVM internal structure and various modules operation mechanism
- Wei Dongshan Digital Photo Frame Project Learning (5) Transplantation of libjpeg-turbo
猜你喜欢
随机推荐
sql注入是什么意思以及防止sql注入?
numpy PIL tensor之间的相互转换
rancher集成ldap,实现统一账号登录
flask-socketio实现websocket通信
LVS-NAT模式【案例实验】
mysql binlog日期解析成yyyy-MM-dd
二叉树的前序遍历、中序遍历、后序遍历和层序遍历
企业云成本管控,你真的做对了吗?
PHICOMM(斐讯)N1盒子 - Armbian5.77(Debian 9)基本配置
韦东山 数码相框 项目学习(五)libjpeg-turbo的移植
Interconversion between numpy PIL tensors
为什么要使用 playwright 做浏览器自动化测试?
openCV第一篇
易购数码类电商商城网页设计与实现项目源码
为什么要使用 playwright 做浏览器自动化测试?
vsftp容器搭建+go开发web用户管理界面(更新于2022.02.23)
能添加任意贴图超级复布局的初级智能文本提示器(超级版)
如何备考PMP才能一次通过?
win下使用vscode+wsl2
initramfs详解-----初识initramfs









