leetcode 152 Maximum Product Subarray
2015-09-22 18:17
375 查看
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.
算法思想:类似,maximum subarray,注意负数与负数相乘变成正数。
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
算法思想:类似,maximum subarray,注意负数与负数相乘变成正数。
代码
int maxProduct(vector<int>& nums) { int max_ending_here_positive = nums[0]>0 ? nums[0] : 1; int max_ending_here_negative = nums[0]<0 ? nums[0] : 1; int max_so_far=nums[0]; for(int i=1;i<nums.size();i++){ int mp=max_ending_here_positive; int mn=max_ending_here_negative; int max_tmp = max(mp*nums[i], mn*nums[i]); max_ending_here_positive = max(max_tmp, 1); max_ending_here_negative = min(min(mp*nums[i], mn*nums[i]), 1); max_so_far = max(max_so_far,max_tmp); } return max_so_far; }
相关文章推荐
- ERROR: Field 'scId' doesn't have a default value
- jquery-ui-1.11 autocomplete使用
- Android微信支付之免jar包集成方式(简单至极)
- hdu5458 LCA+并查集+树状数组
- Qt程序在Mac下需要执行sudo命令的解决办法
- [Netty] - Netty IN ACTION(导言)
- C语言运算符优先级 详细列表
- 如何在STM32F10x_StdPeriph_Template基础上建立自己的MDK工程(一)
- php 设计API之优化 记
- Maven
- Floating Point Optimization(ARM 浮点优化方案)
- 技术做减法
- 一种手机蹭wifi的新思路
- 于ios7在遇到一些发展deprecated问题
- Multipart to single part feature
- Oracle表锁住处理
- 如何实现数字lcd显示效果(原创)
- 自从邓超当了产品经理之后,我整个人都不好了......
- 基础 HTML之目录问题(相对路径和绝对路径区别)
- Multipart polyline to single part lines