题目:
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;
}
};
本文介绍了一种使用贪婪算法寻找股票买卖最佳时机的方法。通过一次遍历股票价格数组,找到买入和卖出的最佳时间点,从而获得最大利润。该算法适用于只允许进行一次交易的情况。
680

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



