[leetcode]: 122. Best Time to Buy and Sell Stock II
来源:互联网 发布:vb 修改网页源代码 编辑:程序博客网 时间:2024/06/03 21:34
1.题目描述
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).
翻译:一个数组表示一只股票n天的价格序列。求能够获得的最大收益。不限交易次数。但最多只能买一手,也就是必须先卖才能再买。
2.分析
把股票价格波动看做一段曲线,理想情况下,只要是价格上涨的阶段都是可以获得的收益。所以计算相邻价格差为正的和即可。
3.代码
python
def maxProfit(self, prices): return sum([max(prices[i]-prices[i-1],0) for i in range(1,len(prices))])
我也真的是有点傻,把解题跟实际操作搞混了,所以自己写的时候是没有想到可以不管交易次数的(要手续费的嘛)。还是贴一下代码吧。
int maxProfit(vector<int>& prices) { if (prices.empty()) return 0; int low = prices[0]; int high = prices[0]; int profit = 0; bool isbuy = false; //在每个阶段最低点买入,最高点卖出 for (int i=1;i<prices.size();i++) { if (prices[i] >= prices[i - 1])//上涨或持平趋势 { isbuy = true;//上涨就买并保持持有状态 high = prices[i];//记录最高位价格 } else//下跌趋势 { if (isbuy) { profit += high - low; isbuy = false;//卖出 } low = prices[i];//记录最低位价格 } } if(isbuy)//最后买的一手在最后一天卖掉 profit += high - low; return profit;}
0 0
- LeetCode 122. Best Time to Buy and Sell Stock II
- [Leetcode] 122. Best Time to Buy and Sell Stock II
- [leetcode] 122.Best Time to Buy and Sell Stock II
- 【leetcode】122.Best Time to Buy and Sell Stock II
- 【LeetCode】122.Best Time to Buy and Sell Stock II
- [leetcode] 122. Best Time to Buy and Sell Stock II
- LeetCode #122. Best Time to Buy and Sell Stock II
- 122. Best Time to Buy and Sell Stock II LeetCode
- [LeetCode]122. Best Time to Buy and Sell Stock II
- Leetcode 122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- LeetCode 122. Best Time to Buy and Sell Stock II
- LeetCode *** 122. Best Time to Buy and Sell Stock II
- leetcode-122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- leetcode 122. Best Time to Buy and Sell Stock II
- 【LeetCode】122. Best Time to Buy and Sell Stock II
- LeetCode - 122. Best Time to Buy and Sell Stock II
- 谷歌浏览器慎用有道词典插件(<audio></audio>)
- Find the Duplicate Number
- 最全的Java笔试题库之选择题篇-总共234道【61~120】
- 1 NXP的BLE协议栈软件架构与应用层代码分析
- 4866: [Ynoi2017]由乃的商场之旅
- [leetcode]: 122. Best Time to Buy and Sell Stock II
- POJ3421_X-factor Chains_素因子分解&&排列组合
- 云服务器lnmp环境一键安装出现错误
- SpringMVC注解配置Swagger2步骤及相关知识点
- centos版本阿里云服务器安装naginx以及相关配置
- JavaScript基础之简介
- bitmap格式分析
- ldd命令浅析
- JNI和C++调用dll效率比较