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.只能买一次卖一次
http://www.lintcode.com/en/problem/best-time-to-buy-and-sell-stock/
Discussion
扫描一遍,记录localmin,拿当前价格减去localmin,返回最大利润。
Solution
class Solution {
public:
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
int maxProfit(vector<int> &prices) {
// write your code here
if(prices.size() == 0) return 0;
int result = 0;
int localmin = prices[0];
for(int i=1; i<prices.size(); i++) {
if(prices[i] - localmin > result)
result = prices[i]-localmin;
localmin = min(prices[i], localmin);
}
return result;
}
};
int maxProfit(vector<int> &prices) {
if(prices.empty()) return 0;
int max_profit = 0;
int local_min = INT_MAX;
for(auto const& cur : prices) {
max_profit = max(max_profit, cur-local_min);
local_min = min(cur, local_min);
}
return max_profit;
}