题目:
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) {
int length = prices.size();
if(length <2)
return 0;
int curMin = prices[0];
int maxProfit = 0;
for(int i=1; i<length; i++)
{
curMin = min(curMin, prices[i]);
maxProfit = max(maxProfit, prices[i] - curMin);
}
return maxProfit;
}
};
另外,这道题目还有很多扩展,
在下面这个博客里面有讲到:
http://liangjiabin.com/blog/2015/04/leetcode-best-time-to-buy-and-sell-stock.html