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) {
vector<int> maxs(prices.size());
vector<int> mins(prices.size());
// Get min from left to right at what time we may buy.
for(int ii = 0; ii < prices.size(); ii ++) {
if(ii == 0) {
mins[ii] = prices[ii];
}
else {
mins[ii] = min(mins[ii - 1], prices[ii]);
}
}
// Get max from right to left at what time we may sell.
for(int ii = prices.size() - 1; ii >= 0; ii --) {
if(ii == prices.size() - 1) {
maxs[ii] = prices[ii];
}
else {
maxs[ii] = max(maxs[ii + 1], prices[ii]);
}
}
int maxgap = 0;
for(int ii = 0; ii < maxs.size(); ii ++) {
if(maxgap < maxs[ii] - mins[ii]) {
maxgap = maxs[ii] - mins[ii];
}
}
return maxgap;
}
};
本文介绍了一个算法,用于在仅允许一次股票交易的情况下找到最大利润。通过使用两个辅助数组,分别从左到右获取最低购买价格和从右到左获取最高卖出价格,该算法能够高效地计算出最大可能利润。
653

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



