题目:
维护两个值即可,一个是当前最低的价格,一个是历史最大利润.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #include <algorithm> #include <climits> #include <vector> using std::vector;
class Solution { public: int maxProfit(vector<int> &prices) {
int n = prices.size(); int max_profit = 0; int min_price = INT_MAX; for (int i = 0; i < n; i++) { max_profit = std::max(prices[i] - min_price, max_profit); min_price = std::min(prices[i], min_price); } return max_profit; } };
|