[leetcode]Best Time to Buy and Sell Stock I&II
来源:互联网 发布:java 中声明short定义 编辑:程序博客网 时间:2024/05/06 21:58
public int maxProfit(int[] prices) { int len=prices.length; if(len==2) return prices[1]>prices[0]?prices[1]-prices[0]:0; int sum=0,tmp=0; int fast=0,slow=0; for(int i=0;i<len-1;i++){ if(prices[i+1]>=prices[i]) fast=i+1; else{ if(fast>slow) tmp=prices[fast]-prices[slow]; if(tmp>sum) sum=tmp; slow=i+1; } } return sum; }
I解题思路
这道题有点类似于最大子数组之和。从前后到遍历数组的时候,求出截止到这个数组可以获得的最大利润。公式是spotrate=a[i]-a[i-1]+spotrate.后面的soptrate是a[i-1]的最大利润。如果spotrate<0,就让spotrate=0就好了。然后设置一个变量记录最大的spotrate。遍历到下标2时,最大利润spotrate=5-3+1=3,也等于5-2;遍历到下标3时,最大利润spotrate=1-5+3=-1,所以让spotrate=0,这个点卖的话最大利润只能是0;遍历到下标4时,最大利润spotrate=5-1+0=4;大于刚才的最大利润3,所以最大利润是4。这样在O(n)就可以求出最大利润。空间复杂度是O(1);
public int maxProfit(int[] prices) { int len=prices.length; int sum=0,spotrate=0; for(int i=1;i<len;i++){ spotrate=Math.max(prices[i]-prices[i-1]+spotrate,0); if(spotrate>sum) sum=spotrate; } return sum; }
II解题思路
刚开始的思路是,把这些股价分段计算出每一个上升段的最大差值,然后写的程序。后来发现只需要后项直接减去前项就可以(后项比前项大),sum = sum+a[i+1]-a[i](if a[i+1]>a[i])思路一程序,可用来对相同问题,做一个代码段。
public class Solution { public int maxProfit(int[] prices) { int len=prices.length; int sum=0; int fast=0,slow=0; for(int i=0;i<len-1;i++){ if(prices[i+1]>=prices[i]) fast=i+1; else{ if(fast>slow) sum+=prices[fast]-prices[slow]; slow=i+1; } } if(fast==len-1) sum+=prices[fast]-prices[slow]; return sum; }}
思路二代码:最简单,后项减前项 伪代码
class Solution: # @param prices, a list of integer # @return an integer def maxProfit(self, prices): ans = 0 for i in range(0,len(prices)-1): if (prices[i+1]-prices[i]>0): ans = ans + prices[i+1]-prices[i] return ans
0 0
- leetcode-Best Time to Buy and Sell Stock I II
- [leetcode]Best Time to Buy and Sell Stock I&II
- Best Time to Buy and Sell Stock I & II & III
- Best Time to Buy and Sell Stock I && II && III
- Best Time to Buy and Sell Stock I II III
- Best Time to Buy and Sell Stock I && II && III
- Best Time to Buy and Sell Stock I II III
- Best Time to Buy and Sell Stock I, II
- best-time-to-buy-and-sell-stock i &ii
- leetcode:Best Time to Buy and Sell Stock I II II
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- Leetcode: Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock II
- LeetCode : Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock II
- [LeetCode] Best Time to Buy and Sell Stock II
- leetcode 61: Best Time to Buy and Sell Stock II
- poj1251
- Zynq高速串行CMOS接口设计与实现
- 在c++代码中执行bat文件
- freopen和fopen的在ACM竞赛中的简单使用
- Qt之国际化(系统文本-QMessageBox按钮、QLineEdit右键菜单等)
- [leetcode]Best Time to Buy and Sell Stock I&II
- web学习-瀑布流布局(2)
- Sublime Text2一些常用快捷键
- 【HDU1754】I HATE IT,线段树练习
- Add Two Numbers
- ios 全局变量的 定义使用
- 关于POI设置SHEET名称以及合并单元格,复制单元格方法
- Android之如果解决Android studio项目里面的类名不能重命名
- UISegmentedControl常见属性及方法