[leetcode-152]Maximum Product Subarray(c)
2015-08-20 23:07
459 查看
问题描述:
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
分析:这道题比较虐心,虽然和求最大子序列和很类似,但是要复杂很多。当我们从前向后遍历时,对于每个节点,我们希望取最大值,最大值的来源有三个,第一个是前一个节点的最大值与该点的乘机,第二个是前一个节点的最小值与该点的乘机。第三个就是该点自身的值。
代码如下:4ms
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
分析:这道题比较虐心,虽然和求最大子序列和很类似,但是要复杂很多。当我们从前向后遍历时,对于每个节点,我们希望取最大值,最大值的来源有三个,第一个是前一个节点的最大值与该点的乘机,第二个是前一个节点的最小值与该点的乘机。第三个就是该点自身的值。
代码如下:4ms
[code]int Min(int a,int b){ return a<b?a:b; } int Max(int a,int b){ return a>b?a:b; } int maxProduct(int* nums, int numsSize) { int min = nums[0]; int max = nums[0]; int res = nums[0]; for(int i = 1;i<numsSize;i++){ int maxmax = max*nums[i]; int minmin = min*nums[i]; max = Max(Max(maxmax,minmin),nums[i]); min = Min(Min(minmin,maxmax),nums[i]); res = Max(max,res); } return res; }
相关文章推荐
- JavaScript运算符
- 04==C语言(分支结构)
- 【二叉堆】k路归并问题(BSOJ1941)
- 【Android高级】应用开发必须要掌握的框架<Volley>
- [2015-08-18] python024
- Swift详解之四-------妈妈再也不用担心我的闭包了
- Infragistics 控件学习
- C++ 小技巧之 字符串字面值拼接
- mysql处理高并发,防止库存超卖
- Pascal's Triangle
- Android WiFi系统
- MySQL+nginx+php环境在ubuntu14.04下的搭建
- 直接从google中引入jquery.js
- linux 命令 - 压缩命令 gzip bzip2
- Linux XZ格式的解压
- Mysql 高性能索引
- Spring Ldap文章链接
- linux下添加PATH环境变量
- [转]jquery后代和子元素的区别
- Struts2笔记――1.常规配置