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.
分析:题目的意思是整个过程中只能买一只股票然后卖出,也可以不买股票。也就是我们要找到一对最低价和最高价,最低价在最高价前面,以最低价买入股票,以最低价卖出股票。
下面三个算法时间复杂度都是O(n)
算法1:顺序扫描股票价格,找到股票价格的第一个上升区间,以区间最低价买入,最高价卖出,后面扫描到上升区间时,根据区间的边界更新最低价和最高价 本文地址
1 class Solution { 2 public: 3 int maxProfit(vector<int> &prices) { 4 // IMPORTANT: Please reset any member data you declared, as 5 // the same Solution instance will be reused for each test case. 6 int len = prices.size(); 7 if(len <= 1)return 0; 8 int i = 0; 9 int ibuy = 0, isell = 0, leastBuy; 10 bool setted = false; 11 while(i < len - 1) 12 { 13 int buy, sell; 14 while(i+1 < len && prices[i+1] < prices[i])i++;//递减区间 15 buy = i++; 16 17 while(i < len && prices[i] >= prices[i-1])i++;//递增区间 18 sell = i-1; 19 if(setted == false) 20 { 21 ibuy = buy; 22 isell = sell; 23 leastBuy = buy; 24 setted = true; 25 } 26 else 27 { 28 if(prices[buy] <= prices[ibuy] && prices[sell] - prices[buy] >= prices[isell] - prices[ibuy]) 29 {ibuy = buy; isell = sell;} 30 if(prices[sell] > prices[isell] && prices[buy] > prices[leastBuy]) 31 {isell = sell; ibuy = leastBuy;} 32 if(prices[leastBuy] > prices[buy])leastBuy = buy; 33 } 34 } 35 return prices[isell] - prices[ibuy]; 36 } 37 };