题目链接
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.
解题思路
TODO(有时间补上,先把自己的leetcode代码写上供参考)
解题代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
int maxProfit = 0;
if (prices.empty()) return 0;
int minEle = prices[0];
int profit = 0;
for(int i =1;i<prices.size();i++) {
profit = (prices[i]-minEle) >= profit? (prices[i]-minEle):profit;
minEle = minEle >=prices[i] ? prices[i]:minEle;
}
return profit;
}
};