题目
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.
题目来自于leetcode,原文链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
有一个数组里面存放着股票每天的价格。你只能做一次操作(某天买入、再找一天卖出)。求最大收益。
分析
由于限制了操作,题目并不是很复杂。最低价格买入,然后找到在以后的日子里最高的价格卖出就行了。
代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
if(len == 0)
return 0;
int max_profit = 0;
int low = prices[0];
vector<int>::iterator it;
for(it = prices.begin() + 1; it != prices.end() ; it++){
if(*it < low)
low = *it;
if(*it - low > max_profit)
max_profit = *it - low;
}
return max_profit;
}
};
本文介绍了一种解决股票买卖问题的算法,旨在寻找一次买入和卖出的最佳时机以获得最大利润。该算法通过遍历价格数组并跟踪最低购买价及最大利润来实现。
681

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



