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) {
if(prices.size() == NULL) return 0;
int low = prices[0];
int ans = 0;
for(int i = 1;i < prices.size();i ++){
if(low > prices[i])
low = prices[i];
else if(low < prices[i])
ans = max(ans,prices[i] - low);
}
return ans;
}
};
本文介绍了一个算法,用于在给定的股票价格数组中,仅通过一次买入和卖出操作,找到可以获得的最大利润。
679

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



