首页 > 代码库 > [leetcode] Best Time to Buy and Sell Stock
[leetcode] Best Time to Buy and Sell Stock
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.
给定一个数组,第i个元素代表股票第i天的价钱,只允许作一次买卖操作,求最大的利润。
从头到尾遍历一遍数组,不断的记录到当前为止的最低股价,并尝试计算以之前的最低股价买入,以当前的价格卖出,不断更新最大利润。时间复杂度o(n)。
代码如下:
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 if (prices.size() == 0) return 0; 5 int buy=prices[0]; 6 int profit = 0; 7 for (int i = 0; i<prices.size(); i++) 8 { 9 if(prices[i] >= buy) 10 { 11 profit = max (prices[i] - buy ,profit); 12 } 13 else 14 { 15 buy = prices[i]; 16 } 17 } 18 return profit; 19 } 20 };
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。