题目
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;
}
};