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.
O(n)的算法。。。没什么好说的
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(prices.empty()) return 0;
int minVal = prices[0];
int result = 0;
for(int i = 1; i < prices.size(); i++){
if(prices[i] > minVal){
result = MAX(result, ( prices[i] - minVal));
}else{
minVal = prices[i];
}
}
return result;
}