【Question】
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 len =prices.size();
if(len<=1) return 0;
int buy;
int sell=0;
buy = prices[0];
int profit=0;
for(int i=1;i<len;i++)
{
sell=prices[i];
if(sell<buy) buy = sell;
else if(sell-buy>profit) profit=sell-buy;
}
return profit;
}
};