121. Best Time to Buy and Sell Stock
来源:互联网 发布:好听的音乐剧歌曲知乎 编辑:程序博客网 时间:2024/06/06 15:38
一、问题:
Say you have an array for which the ith element is the price of a given stock on day i.If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.Example 1:Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)Example 2:Input: [7, 6, 4, 3, 1]Output: 0In this case, no transaction is done, i.e. max profit = 0.
二、解题
(1)暴力解法:
class Solution {public: /* 暴力解法两次循环,找出最大差 超时。 */ int maxProfit(vector<int>& prices) { int max = 0; int n = prices.size(); for (int i = 0; i < n-1; i++) { for (int j = i + 1; j < n; j++) { if (prices[j] - prices[i] > max) { max = prices[j] - prices[i]; } } } return max; }};
class Solution {public: /* 卖出价格从右边遍历,买进从左边遍历。 复杂度1/2*O(n^2) */ int maxProfit(vector<int>& prices) { int max = 0; int n = prices.size(); int i = 0; while (n - 1 > i) { for (int i = 0; i < n - 1; i++) { if (prices[n - 1] - prices[i] > max) { max = prices[n - 1] - prices[i]; } } n--; } return max; }};
阅读全文
0 0
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- springboot踩坑记录-properties中的空格
- Java Static关键字详解
- 柱图颜色渐变
- Hibernate属性级别的注解
- Linux&&shell 总结 三
- 121. Best Time to Buy and Sell Stock
- u3d 逐个点运动,路径运动。 U3d one by one, path motion.
- Excel在统计分析中的应用—第五章—统计指数-Part8-平均指数(几何平均指数)
- [linux]grep命令及遇到的问题总结
- MongoDB常用密令(二)
- u3d 鼠标点击位置,物体移动过去。 U3d mouse clicks position, objects move past.
- Linux 的 splice 和sendfile系统调用
- 2017"百度之星"程序设计大赛-资格赛-1003-度度熊与邪恶大魔王
- Linux服务器--信号