题目链接: https://leetcode.com/problems/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.
思路: the only thing you need to do is maintain a lowest price and the maximum profit.
代码如下:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()==0) return 0;
int Min = INT_MAX, ans = 0;
for(auto val: prices)
Min = min(Min, val), ans = max(ans, val-Min);
return ans;
}
};