LeetCode OJ 122. Best Time to Buy and Sell Stock II
2016-05-21 10:46
127 查看
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
【思路】
相比较上一个题目,这个题目对交易放松了限制,可以做多笔交易,但是在进行下一笔交易之前必须先完成上一笔交易,而且相同交易只能做一次。我的思路是:如果价格在未来上涨,那么我就在当前买入。如果价格在未来下跌,我就在当前卖出。这样的结果就是把数组划分成了一段段的递增序列,在序列的最开始买入,最后卖出。举个例子:[2,1,25,4,5,6,7,2,4,5,1,5]。数组被划分成了5个递增序列,在第一个序列利润为0,第二个序列利润为24,第三个为3,第四个为3,第五个为4.总的利润是34。代码如下:
其实更加简单直观的代码如下:
最后要把所有递增序列中的最大值和最小值的差值加起来,其实这个过程和上述代码的描述是相同的。
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
【思路】
相比较上一个题目,这个题目对交易放松了限制,可以做多笔交易,但是在进行下一笔交易之前必须先完成上一笔交易,而且相同交易只能做一次。我的思路是:如果价格在未来上涨,那么我就在当前买入。如果价格在未来下跌,我就在当前卖出。这样的结果就是把数组划分成了一段段的递增序列,在序列的最开始买入,最后卖出。举个例子:[2,1,25,4,5,6,7,2,4,5,1,5]。数组被划分成了5个递增序列,在第一个序列利润为0,第二个序列利润为24,第三个为3,第四个为3,第五个为4.总的利润是34。代码如下:
public class Solution { public int maxProfit(int[] prices) { int min = 0; int sump = 0; int mp = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] < prices[i-1]){ sump = sump + mp; min = i; mp = 0; } else mp = prices[i] - prices[min]; } return sump + mp; } }
其实更加简单直观的代码如下:
public class Solution { public int maxProfit(int[] prices) { int total = 0; for(int i = 0; i < prices.length-1; i++){ if(prices[i+1] > prices[i]) total += prices[i+1] - prices[i]; } return total; } }
最后要把所有递增序列中的最大值和最小值的差值加起来,其实这个过程和上述代码的描述是相同的。
相关文章推荐
- STM32工程编译后TIM1时钟变慢的解决
- Node.js系列02
- jQuery插件pagination实现无刷新分页
- linux内存,free命令介绍
- GCD创建单例
- 【bzoj4484】【JSOI2015】【最小表示】【拓扑排序+bitset】
- NGUI与粒子系统
- Ubuntu下安装Hudson
- JS验证字符串是否以某一子串结尾,验证字符串是否以某一子串开始;计算字符串长度,中文为2,英文为1,以此累计
- LNK1123: 转换到 COFF 期间失败: 文件无效或损坏
- hdu 3932 Groundhog Build Home
- iOS开发:发布证书无法安装,不能修改"System Roots"钥匙串
- 内存分析工具 MAT 的使用
- cmake使用笔记和Creating CMake Linux projects with Visual Studio
- 数据存储知识(2)--Mysql查看执行计划
- swfkit打包swf文件步骤(图文教程)
- Android圆形头像
- CodeBlocks单步调试入门(百度文库)
- SpringMVC接收ajax传送的参数,后台显示乱码
- 求节点数为n的AVL树的种数