思路:Find i and j that maximizes Aj - Ai, where i < j
显然有O(N^2)的方法,我们可以找到O(N)的算法,就是记录当前扫描过的数据中的最小值。
class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(prices.size() < 2) return 0;
int minPrice = INT_MAX;
int ans = 0;
for(vector<int>::size_type i = 0; i < prices.size(); ++i)
{
if(prices[i] < minPrice)
minPrice = prices[i];
ans = max(ans, prices[i] - minPrice);
}
return ans;
}
};