LeetCode:Maximum Product Subarray
2015-09-17 20:51
351 查看
标题叙述性说明:
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array
the contiguous subarray
思路:从左至右遍历数组,记录下以当前所遍历到的元素结尾的子数组积的最大值和最小值(由于数组里面可能存在负数),同一时候记录下得到的全部最大值中最大的。循环结束时。得到的全部最大值中最大的即为所求。
代码:
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
思路:从左至右遍历数组,记录下以当前所遍历到的元素结尾的子数组积的最大值和最小值(由于数组里面可能存在负数),同一时候记录下得到的全部最大值中最大的。循环结束时。得到的全部最大值中最大的即为所求。
代码:
int Solution::maxProduct(int A[],int n) { if(n == 1) return A[0]; int max_temp = A[0]; int min_temp = A[0]; int result = A[0]; int i; for(i = 1;i < n;i++) { int max_temp2 = max_temp * A[i]; int min_temp2 = min_temp * A[i]; max_temp = max(max_temp2,max(min_temp2,A[i])); min_temp = min(min_temp2,min(max_temp2,A[i])); if(max_temp > result) result = max_temp; } return result; }
相关文章推荐
- TChart
- 网络健身O2O,能火吗?
- 解决properties文件乱码问题
- C++容器deque
- A + B Problem II
- Win10桌面奔溃怎么办?雨林木风Win10奔溃解决方法教程
- 为博客添加目录的配置总结
- BZOJ 2440: [中山市选2011]完全平方数
- btrfs文件系统
- 2015.9.17 initWithName构造函数补充
- nutch源代码阅读心得
- poj 2186 Popular Cows(强连通分量)
- 利用while(code!=EOF){}来实现“无限”循环
- java 泛型实例详解(普通泛型、 通配符、 泛型接口)
- python基础之五种数据类型--2
- 谷歌官方建议笔记——电量
- 1/ 向上转型
- csdn能不能行啊,传个资源我都登陆过了,还是重复让登陆
- IOS征途之三 分类与协议(二)
- 堆排序与优先队列——算法导论(7)