leetcode_best_time_to_buy_and_sell_stock_ii

难度:Medium

解题思路:可以无数次交易。巴菲特告诉我们,每一次涨的时候,都有要获益。
代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size()==0) return 0;
int max_profit = 0;
int min_price = prices.front(), max_price = prices.front();
for(auto it = prices.begin(); it != prices.end(); it++)
{
if(*it > max_price)
{
max_price = *it;
max_profit = max(max_price-min_price, max_profit);
}
if(*it < min_price)
{
min_price = *it;
max_price = *it;
}
}
return max_profit;
}
};

运行结果:6ms,超过48.52%