Share my cpp O(n) solution


  • 0
    Z
    class Solution {
    public:
    int maxProfit(vector<int>& prices) {
    	if(prices.size()<=1)
    		return 0;
        int minBefore=INT_MAX,maxNow=INT_MIN;
        for(int i=0;i<prices.size();i++){
    		if(prices[i]<minBefore)
    			minBefore = prices[i];
    		if(prices[i]-minBefore>maxNow)
    			maxNow = prices[i]-minBefore;
    	}
    	if(maxNow<0)
    		return 0;
    	return maxNow;
    }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.