Coding-Interview-101

Solutions to LeetCode problems filtered with companies, topics and difficulty.

View project on GitHub

Best Time to Buy and Sell Stock


Solution


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