题目地址:
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
题目描述:
...
解决方案:
当前值减之前的数中的最小值得当前值最大利润,再更新最大利润即可
代码:
class Solution {public: int maxProfit(vector & prices) { if (prices.size() < 2) { return 0; } int minPrice = prices.at(0); int maxProfit = 0; for (size_t i = 1; i < prices.size(); i++) { if (minPrice > prices.at(i)) { minPrice = prices.at(i); continue; } int profit = prices.at(i) - minPrice; if (profit > 0 && profit > maxProfit) { maxProfit = profit; } } return maxProfit; }};