Best Time to Buy and Sell Stock

2017/11/23 posted in  leetcode

Say you have an array for which the \(i^{th}\) 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.

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int minPrice=INT_MAX;
        int maxProfit = 0;
        
        for (int i=0; i<prices.size(); i++) {
            minPrice = min(prices[i], minPrice);
            maxProfit = max(maxProfit, prices[i]-minPrice);
        }
        
        return maxProfit;
    }
};