Maximum Product subarray | LeetCode
2015-11-22 19:40
381 查看
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
solution implement by java:
解答思路:每次选择一个元素都是如果该元素使得乘积变大则加入,否则不乘,所以我们需要两个变量分别用来记录在决定当前元素是否需要乘的时候,前面子串所得到的最小值和最大值,每次乘积结果都再用一个变量来存取记录,最后走完整个过程,记录下来的最大值就是结果。
public int maxProduct(int[] nums) {
if(nums.length==1)
return nums[0];
int left=nums[0];
int right=nums[0];
int maxpro=nums[0];
int max,min;
for(int i=1;i<nums.length;++i){
max=Math.max(Math.max(left*nums[i],right*nums[i]),nums[i]);
min=Math.min(Math.min(left*nums[i],right*nums[i]),nums[i]);
maxpro=Math.max(max,maxpro);
left=max;
right=min;
}
return maxpro;
}
For example, given the array
[2,3,-2,4],
the contiguous subarray
[2,3]has the largest product =
6.
solution implement by java:
解答思路:每次选择一个元素都是如果该元素使得乘积变大则加入,否则不乘,所以我们需要两个变量分别用来记录在决定当前元素是否需要乘的时候,前面子串所得到的最小值和最大值,每次乘积结果都再用一个变量来存取记录,最后走完整个过程,记录下来的最大值就是结果。
public int maxProduct(int[] nums) {
if(nums.length==1)
return nums[0];
int left=nums[0];
int right=nums[0];
int maxpro=nums[0];
int max,min;
for(int i=1;i<nums.length;++i){
max=Math.max(Math.max(left*nums[i],right*nums[i]),nums[i]);
min=Math.min(Math.min(left*nums[i],right*nums[i]),nums[i]);
maxpro=Math.max(max,maxpro);
left=max;
right=min;
}
return maxpro;
}
相关文章推荐
- 两个线程与stringbuffer和stringbuiler以及lock synchronized线程测试
- spawn分析
- iOS-UIButton和UIImageView的区别
- 可变参数列表<stdarg.h>
- JAVA解析XML文件(三)---JDOM方式解析
- XML文件读取
- Node.js-require() 源码解读
- 汇总Javascript各种判断脚本(javascript经典例子)
- LayoutSubviews总结
- ListView控件详解
- 编译安装thrift和使用autoconf,automake生成Makefile文件
- 不只是给面试加分 -- Java WeakReference的理解与使用
- 1012. 数字分类 (20)
- 本周心得
- int和Integer有什么区别?
- poj-2140-Herd Sums- 数学规律-连续和为N的方案数
- EL获取list长度!并判断
- docker常用命令
- webview操作方法
- 富文本之某些字体之间的间距特殊调整