classSolution{public:intmaxProfit(vector<int>&prices){intn=prices.size();intmaxProfit=0;// It will store our maximum profit so far// `i`: is our buying day, it will start from go from left to rightfor(inti=0;i<n-1;i++){// `j`: is our selling day, it will use to calcuate the profit, it will start right after the `i`intprofit=0;// It will calculate the profit for each pairfor(intj=i+1;j<n;j++){// profit = selling price - buying priceprofit=prices[j]-prices[i];maxProfit=max(maxProfit,profit);// Take, which is big }}returnmaxProfit;}};
classSolution{public:intmaxProfit(vector<int>&prices){intmaxProfit=0;// It will store our maximum profit so farintminPrice=INT_MAX;// It will store the minimum price till `currentPrice`// Pick each price only oncefor(intcurrentPrice:prices){// Is `currentPrice` is less than the `minPrice`if(currentPrice<minPrice){minPrice=currentPrice;// Update `minPrice`}// Is `currentPrice - minPrice` > `maxProfit`elseif(currentPrice-minPrice>maxProfit){maxProfit=currentPrice-minPrice;// Update `maxProfit`}}returnmaxProfit;}};
Warning
LINK
You are about to visit a link which has been flagged with the above content warnings. Do you wish to continue?