121. Best Time to Buy and Sell Stock

/*We need to find out the maximum difference (which will be the maximum profit) between two numbers in the given array. Also, the second number (selling price) must be larger than the first one (buying price).


In formal terms, we need to find \max(prices[j] - prices[i])max(prices[j]−prices[i]), for every ii and jj such that j > ij>i.
*/
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int min_price = INT_MAX;
        int max_p = 0;
        for(int m:prices)
        {
            if(m < min_price) min_price = m;
            else
            {
                if(m-min_price>max_p) max_p = m-min_price;
            }
        }
        
        return max_p;
    }
};

相关文章:

  • 2021-06-15
  • 2021-06-27
  • 2021-10-19
  • 2021-11-23
  • 2021-09-01
猜你喜欢
  • 2021-05-31
相关资源
相似解决方案