当前位置:网站首页>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;
}
};
边栏推荐
- Jenkins2.328+sonarqube7.9 实现代码自动化检测
- 公司代码学习笔记
- The Sandbox 市场平台将上线 Isla Obscura 第五期 NFT 作品集
- Topic Modeling of Short Texts: A Pseudo-Document View
- 44LVS负载均衡群集-NAT
- The cornerstone of high concurrency: multithreading, daemon threading, thread safety, thread synchronization, mutual exclusion lock, all in one article!...
- apache-activemq-5.14.1
- LVS-NAT模式【案例实验】
- initramfs详解-----初识initramfs
- JVM内部结构图及各模块运行机制总结
猜你喜欢

流程图(1)

MySQL-如何分库分表?一看就懂

孩子坐不住就是不专注?猿辅导揭秘专注力的三大误区

Fiddler基本使用

initramfs详解----设备文件系统

.NET in-depth analysis of the LINQ framework (four: IQueryable, IQueryProvider interface details)

FLIR E95 在8层楼看马路上行驶的CAR的热成像形态?

Incorrect datetime value: '2022-01-01' for function str_to_date

YYGH-BUG-06

iNFTnews | 元宇宙的潜力:一股推动社会进步的力量
随机推荐
问题记录:jenkins构建时报错The goal you specified requires a project to execute but there is no POM in...
粘包与拆包
一些面试的总结
选中按钮上色
常用工具链和虚拟环境-WSL
[Arduino] Reborn Arduino Monk (3)----Arduino function
怎么从零编写一个 v3 版本的 chrome 浏览器插件实现 CSDN 博客网站的暗黑和明亮主题切换?
Conversational Technology!
会话技术!
【静态类型和动态类型 编译检查和运行检查 Objective-C中】
IDEA基本使用-创建和删除项目
236. The binary tree in recent common ancestor
项目管理到底管的是什么?
46LVS+Keepalived群集
【社媒营销】Facebook速推帖子如何运作?值得吗?
可信的SSL证书颁发机构有哪些
Linux定时任务脚本执行时mysqldump备份异常的问题
孩子坐不住就是不专注?猿辅导揭秘专注力的三大误区
工作两年成跳槽高峰期,程序员会在一家公司待多久?
韦东山 数码相框 项目学习(五)libjpeg-turbo的移植