题目:
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 min_date=0,min_price=INT_MAX,max_profit=0;
for(int i=0;i<prices.size();i++){
if(prices[i]<min_price){
min_price=prices[i];
min_date=i;
}
if(i>min_date&&prices[i]-min_price>max_profit)max_profit=prices[i]-min_price;
}
return max_profit;
}
};