From : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
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 profit=0;
for(int i=0, days=prices.size(), buy=INT_MAX; i<days; i++) {
int price = prices[i];
if(price < buy) buy=price;
if(profit < price-buy) {
profit = price-buy;
}
}
return profit;
}
};
本文介绍了一种寻找股票买卖最佳时机以获得最大利润的算法。该算法通过一次遍历价格数组,跟踪最低买入价格和最高卖出价格之间的差额来确定最大利润。
677

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



