121. Best Time to Buy and Sell Stock
做题历程:
- 本题做了不止两次了,本次用时4分钟,独立解出
本题的难度算是比较低的,有点类似dynamic programming的思路。 大概就是寻找之前的最小的点,和当前点相减得到profit,再和全局的max profit对比,正确性还是比较容易想明白的。。。代码如下:
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (prices.size() <= 1) {
return 0;
}
int minimum = prices[0];
int max_profit = 0;
for (int i = 1; i < prices.size(); ++i) {
if (prices[i] < minimum) {
minimum = prices[i];
}
else {
max_profit = max(max_profit, prices[i] - minimum);
}
}
return max_profit;
}
};