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.
扫描,记录并更新最大值
class Solution {
public:
int maxProfit(vector<int> &prices) {
if (!prices.size()) return 0;
int profit = 0, price = prices[0];
for (int i=1; i<prices.size(); i++) {
profit = max(prices[i]-price, profit);
price = min(prices[i], price);
}
return profit;
}
};