1. 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]\}
\]

对于数组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;
}
};

最新文章

  1. Swift - UIBezierPath
  2. Concurrency vs. Parallelism
  3. POJ 3683 Priest John&#39;s Busiest Day (2-SAT)
  4. 理解闭包 js回收机制
  5. 浅谈SDN和NFV之间的关系
  6. Mac环境下svn的使用
  7. monkey学习笔记
  8. 研究CPU的好文章以及博客
  9. Linux apt-get
  10. javascript学习笔记20160121-css选择器
  11. http://begin.lydsy.com/JudgeOnline/problem.php?id=2770(PKU2503 Babelfish)
  12. [JLOI 2015]装备购买
  13. Git的思想和基本工作原理2
  14. 校园生活app结对开发第二天
  15. truffle unbox react 出坑指南
  16. 【shiro】(1)---了解权限管理
  17. Js中处理日期加减天数
  18. Linux命令(十一)gcc
  19. listagg乱码问题
  20. 一个Unix内核级别漏洞(一)

热门文章

  1. Docker从入门到精通(八)——Docker Compose
  2. logging模块学习
  3. 【LeetCode】252. Meeting Rooms 解题报告(C++)
  4. 【LeetCode】884. Uncommon Words from Two Sentences 解题报告(Python)
  5. 【LeetCode】341. Flatten Nested List Iterator 解题报告(Python&C++)
  6. Fast Matrix Operations(UVA)11992
  7. 记一次引入Elasticsearch的系统架构实战
  8. Chapter 20 Treatment-Confounder Feedback
  9. [数据结构]链表相关的实现LinkList.cpp
  10. Spring企业级程序设计 • 【第4章 Spring持久化层和事务管理】