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.
Solution:Code:
<span style="font-size:14px;">class Solution {
public:
int maxProfit(vector<int> &prices) {
const int length = prices.size();
if (length < 2) return 0;
int lowest = prices[0];
int result = 0;
for (int i = 1; i < length; ++i) {
lowest = min(lowest, prices[i]);
result = max(result, prices[i]-lowest);
}
return result;
}
};</span>