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
Idea: record current minimum price, and calculate the current profit. If the current profit is large than previous max profit, update max profit.
class Solution {
public:
int maxProfit(vector<int>& prices) {
if (!prices.size()) return 0;
int ret = 0;
int minp = prices[0];
for(int i =0; i < prices.size(); i++){
minp = min(minp,prices[i]);
ret = max(ret, prices[i] - minp);
}
return ret;
}
};