Say you have an array for which the ith element is the price of a given stock on dayi.
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.
// The maxProfit is the current price minus the min price.
int maxProfit(vector<int>& prices) {
if(prices.size() <= 1) return 0;
int maxProfit = INT_MIN;
int minPriceSoFar = prices[0];
for(int i = 1; i < prices.size(); ++i) {
minPriceSoFar = min(prices[i], minPriceSoFar);
maxProfit = max(maxProfit, prices[i] - minPriceSoFar);
}
return maxProfit;
}
Follow up: output the transaction
vector<int> buyStock(vector<int>& nums) {
if(nums.size() <= 1) return {};
int buy = 0; // buy date
int sell = 0; // sell date
int minPriceSoFar = nums[0];
int maxProfit = 0;
for(int i = 1; i < nums.size(); ++i) {
if(nums[i] < minPriceSoFar) {
buy = i;
minPriceSoFar = nums[i];
} else {
if(maxProfit < nums[i] - minPriceSoFar) {
maxProfit = nums[i] - minPriceSoFar;
sell = i;
}
}
}
return {maxProfit, buy, sell}; // here maybe need one more check: if the maxProfit == 0, buy and sell should all set to 0.
}
本文介绍了一种寻找股票买卖最佳时机以获得最大利润的算法。该算法通过一次遍历找到最低买入价格和最大卖出利润,并提供了输出具体交易日的功能。
283

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



