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.
让标签吓住了。。。dp。。。
其实维护一个最低价,一个最高盈利就行了。。当然了O(1) dp...
class Solution {
public:
int maxProfit(vector<int>& prices) {
int size=prices.size();
if (size<=1)
return 0;
int min_price=prices[0];
int profit=0;
for (int i=1; i<size;i++){
min_price=min(min_price, prices[i]);
profit=max(profit, prices[i]-min_price);
}
return profit;
}
};
410

被折叠的 条评论
为什么被折叠?



