leetcode 152 O(n)解决方案
来源:互联网 发布:淘宝软件下载电脑版 编辑:程序博客网 时间:2024/06/06 12:47
题目大意:寻找一个子序列,使其乘积达到最大。
解决思路:记f[i]为前i个数能得到的最大乘积。递推公式如下:
f[i]=Max(f[i-1],b[i]);b[i]表示含有nums[i]的最大乘积。
为求b[i],构造一个额外数组temp,temp[i]=nums[i]*nums[i-1]….*nums[j]; j=0或者nums[j-1]=0, nums[i]=0时,temp[i]=0;
用first记录第一次出现负数的位置(如果有0出现,first要重置)。
不难得出:
if temp[i]>=0||i==first , b[i] = temp[i];
else , b[i]=temp[i]/temp[first].
贴代码:
public int maxProduct(int[] nums) { int[] temp = new int[nums.length]; int re = nums[0]; temp[0]=re; int first = -1; if(re<0) first=0; for(int i=1;i<nums.length;i++){ if(temp[i-1]!=0) temp[i]=temp[i-1]*nums[i]; else{ temp[i]=nums[i]; first=-1; } if(temp[i]>re) re=temp[i]; else if(first!=-1){ if(temp[i]/temp[first]>re) re = temp[i]/temp[first]; } if(nums[i]<0&&first==-1){ first=i; } } return re; }
阅读全文
0 0
- leetcode 152 O(n)解决方案
- LeetCode OJ平台上Maximum Subarray题目O(n)复杂度解决方案
- 3Sum | LeetCode O(N*N) Solution
- [LeetCode] Longest Palindromic Substring - O(n)
- leetcode Longest Valid Parentheses O(n)解法
- LeetCode 53. Maximum Subarray O(n)实现
- LeetCode 84. Maximal Rectanglea (O(n)实现)
- leetcode: Merge Sorted Array O(n)解法
- [LeetCode] Pow(x,n) O(logN)
- LeetCode Maximum Gap的O(N)解法
- 268. Missing Number(leetcode O(n))
- LeetCode: Longest Valid Parentheses O(n)时间 O(1)空间
- LeetCode 135. Candy (O(n)时间 O(n)和O(1)空间的两种实现)
- Longest Palindromic Substring[leetcode] O(n^2)的DP和O(n)的算法
- LeetCode, Median of Two Sorted Arrays, Java Solution, O(m+n), O(log(m+n))
- Leetcode - Array - 1. Two Sum (水题,O[n]和O[n^2]实现)
- O(n)
- LeetCode Reorder List O(n) space空间解法
- android stuido环境运行出错
- LA4329 树状数组
- SprintBoot学习笔记(5):解决中文乱码问题
- 第二章 SQL命令参考-ALTER FILESPACE
- Redis高级特性及应用场景
- leetcode 152 O(n)解决方案
- rtabmap (一)
- 软考初级程序员-进制转换
- 开灯问题
- 【51nod】1021 石子归并
- 图解HTTP(五)
- bzoj 1688: [Usaco2005 Open]Disease Manangement 疾病管理 状压
- [USACO08JAN]电话线
- Chrome扩展程序——TabCopy:一键复制网页标题和网址