Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
从后面开始遍历,找出具有最大的 aj-ai , j >= i
class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(prices.size() == 0)
return 0;
int m = prices[prices.size() - 1], max_diff = 0;
for(int i=prices.size() - 1 ; i>=0; i--){
if(m - prices[i] > max_diff)
max_diff = m - prices[i];
m = max(prices[i], m);
}
return max_diff;
}
};