My simple c++ solution


  • 0
    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            if(prices.size()==0) return 0;
            vector<int> min(prices.size());
            int ret=0;
            min[0]=prices[0];
            for(int i=1;i<prices.size();i++){
                if(prices[i]<min[i-1]){
                    min[i]=prices[i];
                }
               else min[i]=min[i-1];
               if(prices[i]-min[i-1]>ret) ret=prices[i]-min[i-1];
            }
            return ret;  
        }
    };
    

    And in this problem, array may not needed.

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

Log in to reply
 

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