【刷题-LeetCode】152 Maximum Product Subarray
2024-09-05 06:19:19
- Maximum Product Subarray
Given an integer array nums
, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
解法 动态规划。需要设置两个dp数组,分别保存到位置i的最大和最小连续乘积,这是因为最小的乘积可能是负的,如果再乘上一个负数会变成比较大数
\[\mathrm{dp\_max}[0] = \mathrm{dp\_min}[0] = \mathrm{nums}[0]\\
\mathrm{dp\_max[i]} = \max\{\mathrm{nums}[i], \mathrm{dp\_max}[i-1]*\mathrm{nums}[i], \mathrm{dp\_min}[i-1]*\mathrm{nums}[i]\}\\
\mathrm{dp\_min[i]} = \min\{\mathrm{nums}[i], \mathrm{dp\_max}[i-1]*\mathrm{nums}[i], \mathrm{dp\_min}[i-1]*\mathrm{nums}[i]\}
\]
\mathrm{dp\_max[i]} = \max\{\mathrm{nums}[i], \mathrm{dp\_max}[i-1]*\mathrm{nums}[i], \mathrm{dp\_min}[i-1]*\mathrm{nums}[i]\}\\
\mathrm{dp\_min[i]} = \min\{\mathrm{nums}[i], \mathrm{dp\_max}[i-1]*\mathrm{nums}[i], \mathrm{dp\_min}[i-1]*\mathrm{nums}[i]\}
\]
对于数组dp_max和dp_min,每次更新只用两个连续的数,因此可以将空间复杂度优化为\(O(1)\)
class Solution {
public:
int maxProduct(vector<int>& nums) {
int pre_f = nums[0], pre_g = nums[0];
int res = pre_f;
for(int i = 1; i < nums.size(); ++i){
int tmp1 = max(nums[i], max(pre_f*nums[i], pre_g*nums[i]));
int tmp2 = min(nums[i], min(pre_f*nums[i], pre_g*nums[i]));
res = max(res, tmp1);
pre_f = tmp1;
pre_g = tmp2;
}
return res;
}
};
最新文章
- Swift - UIBezierPath
- Concurrency vs. Parallelism
- POJ 3683 Priest John&#39;s Busiest Day (2-SAT)
- 理解闭包 js回收机制
- 浅谈SDN和NFV之间的关系
- Mac环境下svn的使用
- monkey学习笔记
- 研究CPU的好文章以及博客
- Linux apt-get
- javascript学习笔记20160121-css选择器
- http://begin.lydsy.com/JudgeOnline/problem.php?id=2770(PKU2503 Babelfish)
- [JLOI 2015]装备购买
- Git的思想和基本工作原理2
- 校园生活app结对开发第二天
- truffle unbox react 出坑指南
- 【shiro】(1)---了解权限管理
- Js中处理日期加减天数
- Linux命令(十一)gcc
- listagg乱码问题
- 一个Unix内核级别漏洞(一)
热门文章
- Docker从入门到精通(八)——Docker Compose
- logging模块学习
- 【LeetCode】252. Meeting Rooms 解题报告(C++)
- 【LeetCode】884. Uncommon Words from Two Sentences 解题报告(Python)
- 【LeetCode】341. Flatten Nested List Iterator 解题报告(Python&C++)
- Fast Matrix Operations(UVA)11992
- 记一次引入Elasticsearch的系统架构实战
- Chapter 20 Treatment-Confounder Feedback
- [数据结构]链表相关的实现LinkList.cpp
- Spring企业级程序设计 • 【第4章 Spring持久化层和事务管理】