《leetCode》:Maximum Product Subarray
2016-03-17 21:31
239 查看
题目
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.
思路
算法:最大产品值主要由两个因素决定:第一为 0元素,第二为负数的个数当在遍历的过程中,遇到了 0元素,则采用以下的决策
1)如果此时的值为负数,则lowpoint逐渐向highpoint靠拢,使得当前值为正数
2)如果此时的值为正数,则抛弃掉此时的值,lowpoint跳过这个0元素的位置指向第一个非零值 ,继续运算判断
还有:在遍历完整个数组之后,如果当前值为负数,也要lowpoint逐渐向highpoint靠拢,使得当前值为正数
在上面的过程中,总要不断的更新最大值
实现代码如下:
int max(int a,int b){ return a>b?a:b; } int maxProduct(int* nums, int numsSize) { if(nums==NULL||numsSize<1){ return 0; } if(numsSize==1){ return nums[0]; } //用双指针来进行 int lowpoint=0; int highpoint=0; int maxValue=INT_MIN; int curValue=1; while(highpoint<numsSize){ if(nums[highpoint]==0&&curValue<0&&lowpoint<highpoint-1){ for(;curValue<0&&lowpoint<highpoint-1;lowpoint++){//直到curValue为正 curValue/=nums[lowpoint]; maxValue=max(maxValue,curValue); } } else if(nums[highpoint]==0){ maxValue=max(maxValue,0);//注意 highpoint++; lowpoint=highpoint; curValue=1; } else{ curValue*=nums[highpoint++]; maxValue=max(maxValue,curValue); } } for(;curValue<0&&lowpoint<numsSize-1;lowpoint++){//当curValue小于零时,则增大lowpoint curValue/=nums[lowpoint]; maxValue=max(maxValue,curValue); } return maxValue; }
相关文章推荐
- 浅谈 C++ 中的 new/delete
- Android自定义弹出框AlertDialog
- 使用FreeMarker的Web Project例子
- Reverse Linked List II
- PB事件:pbm_enupdate
- python标准库学习1-SYS
- 从客户端中检测到有潜在危险的 Request.Form 值 设置 ValidateRequest="false" 不管用
- IBM Bluemix试用到期后绑定信用卡继续免费使用
- PowerDesigner 学习笔记
- noip2011普及组:统计单词
- C++中cin、cin.get()、cin.getline()、getline()、gets()等函数的用法----细节决定成败 (sort用法)
- ListView与RecyclerView的区别
- 3招搞定android内存泄漏
- iOS 根据自己项目 说说对xml解析的理解
- Linux常用指令
- 编程之美-买书问题
- Caffe + Ubuntu 15.04 + CUDA 7.5 新手安装配置指南
- NSURLConnect的使用
- c++复习要点总结之三 ——构造函数
- cssAndHtml