Leetcode-152. Maximum Product Subarray
来源:互联网 发布:linux 清空回收站 编辑:程序博客网 时间:2024/05/02 04:32
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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
.
public class Solution { public int maxProduct(int[] nums) { int max = nums[0]; int[] positive = new int[nums.length]; int[] negetive = new int[nums.length]; positive[0] = 1; negetive[0] = 1; if(nums[0] > 0) positive[0] = nums[0]; else if(nums[0] < 0) negetive[0] = nums[0]; for(int i = 1; i <nums.length ; i ++){ if(nums[i] > 0){ positive[i] = positive[i-1] * nums[i]; if(negetive[i-1] != 1) negetive[i] = negetive[i-1] * nums[i]; else negetive[i] = 1; max = positive[i] > max ? positive[i] : max; }else if(nums[i] < 0){ if(negetive[i-1] != 1) { positive[i] = negetive[i-1] * nums[i]; max = positive[i] > max ? positive[i] : max; } else positive[i] = 1; negetive[i] = nums[i] * positive[i-1]; max = negetive[i] > max ? negetive[i] : max; } else{ positive[i] = 1; negetive[i] = 1; max = max >= 0 ? max : 0; } } return max; }}
0 0
- LeetCode 152. Maximum Product Subarray
- [leetcode] 152.Maximum Product Subarray
- [LeetCode]152. Maximum Product Subarray
- leetcode:152. Maximum Product Subarray
- leetcode 152. Maximum Product Subarray
- 152. Maximum Product Subarray LeetCode
- [leetcode] 152. Maximum Product Subarray
- LeetCode *** 152. Maximum Product Subarray
- LeetCode 152. Maximum Product Subarray
- leetcode.152. Maximum Product Subarray
- LeetCode-152.Maximum Product Subarray
- LeetCode - 152. Maximum Product Subarray
- [Leetcode]152. Maximum Product Subarray
- LeetCode 152. Maximum Product Subarray
- leetcode:152. Maximum Product Subarray
- [leetcode]152. Maximum Product Subarray
- LeetCode 152. Maximum Product Subarray
- [LeetCode] 152. Maximum Product Subarray
- 微服务的可变和不可变
- C++学习摘要3
- 托盘操作
- ejabberd为游戏免除注册限制
- ELF文件和BIN文件
- Leetcode-152. Maximum Product Subarray
- Android中的四大组件
- stosd,stosb,stosw汇编指令
- CentOS服务器网络配置
- 嵌入式概述
- hdu 4283 (区间dp)
- 并查集初步小结。。
- Android Studio 常用快捷键 及常用使用技巧
- play框架用起来(3)